id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_good_1898_1
package io.onedev.server.model.support.inputspec.textinput; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.validation.ValidationException; import com.google.common.collect.Lists; import io.onedev.server.model.support.inputspec.InputSpec; import io.onedev.server.model.support.inputspec.textinput.defaultvalueprovider.DefaultValueProvider; public class TextInput { public static String getPropertyDef(InputSpec inputSpec, Map<String, Integer> indexes, String pattern, DefaultValueProvider defaultValueProvider) { pattern = InputSpec.escape(pattern); int index = indexes.get(inputSpec.getName()); StringBuffer buffer = new StringBuffer(); inputSpec.appendField(buffer, index, "String"); inputSpec.appendCommonAnnotations(buffer, index); if (!inputSpec.isAllowEmpty()) buffer.append(" @NotEmpty\n"); if (pattern != null) buffer.append(" @Pattern(regexp=\"" + pattern + "\", message=\"Should match regular expression: " + pattern + "\")\n"); inputSpec.appendMethods(buffer, index, "String", null, defaultValueProvider); return buffer.toString(); } public static Object convertToObject(List<String> strings) { if (strings.size() == 0) return null; else if (strings.size() == 1) return strings.iterator().next(); else throw new ValidationException("Not eligible for multi-value"); } public static List<String> convertToStrings(Object value) { if (value instanceof String) return Lists.newArrayList((String)value); else return new ArrayList<>(); } }
./CrossVul/dataset_final_sorted/CWE-74/java/good_1898_1
crossvul-java_data_bad_3891_1
package io.dropwizard.validation.selfvalidating; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The annotated element has methods annotated by * {@link io.dropwizard.validation.selfvalidating.SelfValidation}. * Those methods are executed on validation. */ @Documented @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = SelfValidatingValidator.class) public @interface SelfValidating { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
./CrossVul/dataset_final_sorted/CWE-74/java/bad_3891_1
crossvul-java_data_bad_5080_0
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.dataprovider.sql.dialect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.dashbuilder.dataprovider.sql.model.Column; import org.dashbuilder.dataprovider.sql.model.Condition; import org.dashbuilder.dataprovider.sql.model.CoreCondition; import org.dashbuilder.dataprovider.sql.model.CreateTable; import org.dashbuilder.dataprovider.sql.model.Delete; import org.dashbuilder.dataprovider.sql.model.DynamicDateColumn; import org.dashbuilder.dataprovider.sql.model.FixedDateColumn; import org.dashbuilder.dataprovider.sql.model.FunctionColumn; import org.dashbuilder.dataprovider.sql.model.Insert; import org.dashbuilder.dataprovider.sql.model.LogicalCondition; import org.dashbuilder.dataprovider.sql.model.SQLStatement; import org.dashbuilder.dataprovider.sql.model.Select; import org.dashbuilder.dataprovider.sql.model.SimpleColumn; import org.dashbuilder.dataprovider.sql.model.SortColumn; import org.dashbuilder.dataprovider.sql.model.Table; import org.dashbuilder.dataset.ColumnType; import org.dashbuilder.dataset.filter.CoreFunctionType; import org.dashbuilder.dataset.filter.LogicalExprType; import org.dashbuilder.dataset.group.AggregateFunctionType; import org.dashbuilder.dataset.group.DateIntervalType; import org.dashbuilder.dataset.sort.SortOrder; import static org.dashbuilder.dataprovider.sql.SQLFactory.*; public class DefaultDialect implements Dialect { private static final String AND = " AND "; @Override public String[] getExcludedColumns() { return new String[] {}; } @Override public String getColumnSQL(Column column) { if (column instanceof FunctionColumn) { return getFunctionColumnSQL((FunctionColumn) column); } else if (column instanceof SortColumn) { return getSortColumnSQL((SortColumn) column); } else if (column instanceof DynamicDateColumn) { return getDynamicDateColumnSQL((DynamicDateColumn) column); } else if (column instanceof FixedDateColumn) { return getFixedDateColumnSQL((FixedDateColumn) column); } else if (column instanceof SimpleColumn) { return getSimpleColumnSQL((SimpleColumn) column); } else { return getColumnNameSQL(column.getName()); } } @Override public String getColumnTypeSQL(Column column) { switch (column.getType()) { case NUMBER: { return "NUMERIC(28,2)"; } case DATE: { return "TIMESTAMP"; } default: { return "VARCHAR(" + column.getLength() + ")"; } } } @Override public String convertToString(Object value) { try { return value == null ? null : (String) value; } catch (ClassCastException e) { return value.toString(); } } @Override public Double convertToDouble(Object value) { try { return value == null ? null : ((Number) value).doubleValue(); } catch (ClassCastException e) { return Double.parseDouble(value.toString()); } } @Override public Date convertToDate(Object value) { try { return value == null ? null : (Date) value; } catch (ClassCastException e) { throw new IllegalArgumentException("Not a java.util.Date: " + value + " (" + value.getClass().getName() + ")"); } } @Override public String getTableSQL(SQLStatement<?> stmt) { Table table = stmt.getTable(); String name = getTableNameSQL(table.getName()); if (StringUtils.isBlank(table.getSchema())) { return name; } else{ return getSchemaNameSQL(table.getSchema()) + "." + name; } } @Override public String getTableNameSQL(String name) { return name; } @Override public String getSchemaNameSQL(String name) { return name; } @Override public String getSimpleColumnSQL(SimpleColumn column) { String result = getColumnNameSQL(column.getName()); if (column.getFunctionType() != null) { result = getColumnFunctionSQL(result, column.getFunctionType()); } return result; } @Override public String getFunctionColumnSQL(FunctionColumn column) { if (FunctionColumn.LOWER.equals(column.getFunction())) { return getLowerFunctionSQL(column.getColumns()[0]); } if (FunctionColumn.CONCAT.equals(column.getFunction())) { return getConcatFunctionSQL(column.getColumns()); } if (FunctionColumn.YEAR.equals(column.getFunction())) { return getDatePartFunctionSQL("YEAR", column.getColumns()[0]); } if (FunctionColumn.MONTH.equals(column.getFunction())) { return getDatePartFunctionSQL("MONTH", column.getColumns()[0]); } if (FunctionColumn.DAY.equals(column.getFunction())) { return getDatePartFunctionSQL("DAY", column.getColumns()[0]); } if (FunctionColumn.HOUR.equals(column.getFunction())) { return getDatePartFunctionSQL("HOUR", column.getColumns()[0]); } if (FunctionColumn.MINUTE.equals(column.getFunction())) { return getDatePartFunctionSQL("MINUTE", column.getColumns()[0]); } if (FunctionColumn.SECOND.equals(column.getFunction())) { return getDatePartFunctionSQL("SECOND", column.getColumns()[0]); } throw new IllegalArgumentException("Column function not supported: " + column.getFunction()); } @Override public String getLowerFunctionSQL(Column column) { String columnSQL = getColumnSQL(column); return "LOWER(" + columnSQL + ")"; } @Override public String getConcatFunctionSQL(Column[] columns) { return getConcatFunctionSQL(columns, "(", ")", " || "); } public String getConcatFunctionSQL(Column[] columns, String begin, String end, String separator) { StringBuilder out = new StringBuilder(); out.append(begin); for (int i = 0; i < columns.length; i++) { if (i > 0) out.append(separator); Column column = columns[i]; ColumnType type = column.getType(); if (ColumnType.LABEL.equals(type) || ColumnType.TEXT.equals(type)) { out.append("'").append(column.getName()).append("'"); } else { // Cast needed out.append(getColumnCastSQL(column)); } } out.append(end); return out.toString(); } public String getColumnCastSQL(Column column) { String columnSQL = getColumnSQL(column); return "CAST(" + columnSQL + " AS VARCHAR)"; } @Override public String getDatePartFunctionSQL(String part, Column column) { String columnSQL = getColumnSQL(column); return "EXTRACT(" + part + " FROM " + columnSQL + ")"; } @Override public String getSortColumnSQL(SortColumn sortColumn) { Column column = sortColumn.getSource(); String columnSQL = getColumnSQL(column); // Always order by the alias (if any) if (!StringUtils.isBlank(column.getAlias())) { columnSQL = getAliasForStatementSQL(column.getAlias()); } return columnSQL + " " + getSortOrderSQL(sortColumn.getOrder()); } @Override public String getSortOrderSQL(SortOrder order) { if (SortOrder.ASCENDING.equals(order)) { return "ASC"; } if (SortOrder.DESCENDING.equals(order)) { return "DESC"; } throw new IllegalArgumentException("Sort order not supported: " + order); } /** * The text conversion of a date column is very DB specific. * A mechanism combining concat and extract functions is used by default. * Depending on the DB dialect a more polished approach can be used. * For instance, <ul> * <li>In Oracle and Postgres the 'to_char' function is used.</li> * <li>In Mysql, 'date_format'</li> * <li>In H2, the 'to_char' function is not used as it's only available since version 1.3.175 and we do need to support older versions.</li> * </ul> */ @Override public String getDynamicDateColumnSQL(DynamicDateColumn column) { Column dateColumn = toChar(column); return getColumnSQL(dateColumn); } public Column toChar(DynamicDateColumn column) { Column target = column(column.getName()); DateIntervalType type = column.getDateType(); Column SEPARATOR_DATE = column("-", ColumnType.TEXT, 3); Column SEPARATOR_EMPTY = column(" ", ColumnType.TEXT, 3); Column SEPARATOR_TIME = column(":", ColumnType.TEXT, 3); if (DateIntervalType.SECOND.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour(), SEPARATOR_TIME, target.minute(), SEPARATOR_TIME, target.second()); } if (DateIntervalType.MINUTE.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour(), SEPARATOR_TIME, target.minute()); } if (DateIntervalType.HOUR.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour()); } if (DateIntervalType.DAY.equals(type) || DateIntervalType.WEEK.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day()); } if (DateIntervalType.MONTH.equals(type) || DateIntervalType.QUARTER.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month()); } if (DateIntervalType.YEAR.equals(type) || DateIntervalType.DECADE.equals(type) || DateIntervalType.CENTURY.equals(type) || DateIntervalType.MILLENIUM.equals(type)) { return target.year(); } throw new IllegalArgumentException("Group '" + target.getName() + "' by the given date interval type is not supported: " + type); } @Override public String getFixedDateColumnSQL(FixedDateColumn column) { Column target = column(column.getName()); DateIntervalType type = column.getDateType(); if (DateIntervalType.SECOND.equals(type)) { return getColumnSQL(target.second()); } if (DateIntervalType.MINUTE.equals(type)) { return getColumnSQL(target.minute()); } if (DateIntervalType.HOUR.equals(type)) { return getColumnSQL(target.hour()); } if (DateIntervalType.DAY_OF_WEEK.equals(type)) { return getColumnSQL(target.day()); } if (DateIntervalType.MONTH.equals(type)) { return getColumnSQL(target.month()); } if (DateIntervalType.QUARTER.equals(type)) { // Emulated using month and converted to quarter during the data set post-processing return getColumnSQL(target.month()); } throw new IllegalArgumentException("Interval size '" + type + "' not supported for " + "fixed date intervals. The only supported sizes are: " + StringUtils.join(DateIntervalType.FIXED_INTERVALS_SUPPORTED, ",")); } @Override public String getColumnNameSQL(String name) { return name; } @Override public String getColumnNameQuotedSQL(String name) { return "\"" + name + "\""; } @Override public String getAliasForColumnSQL(String alias) { return "\"" + alias + "\""; } @Override public String getAliasForStatementSQL(String alias) { return "\"" + alias + "\""; } @Override public String getConditionSQL(Condition condition) { if (condition instanceof CoreCondition) { return getCoreConditionSQL((CoreCondition) condition); } if (condition instanceof LogicalCondition) { return getLogicalConditionSQL((LogicalCondition) condition); } throw new IllegalArgumentException("Condition type not supported: " + condition); } @Override public String getCoreConditionSQL(CoreCondition condition) { String columnSQL = getColumnSQL(condition.getColumn()); CoreFunctionType type = condition.getFunction(); Object[] params = condition.getParameters(); if (CoreFunctionType.IS_NULL.equals(type)) { return getIsNullConditionSQL(columnSQL); } if (CoreFunctionType.NOT_NULL.equals(type)) { return getNotNullConditionSQL(columnSQL); } if (CoreFunctionType.EQUALS_TO.equals(type)) { return getIsEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_EQUALS_TO.equals(type)) { return getNotEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_EQUALS_TO.equals(type)) { return getNotEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LIKE_TO.equals(type)) { return getLikeToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.GREATER_THAN.equals(type)) { return getGreaterThanConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.GREATER_OR_EQUALS_TO.equals(type)) { return getGreaterOrEqualsConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LOWER_THAN.equals(type)) { return getLowerThanConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LOWER_OR_EQUALS_TO.equals(type)) { return getLowerOrEqualsConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.BETWEEN.equals(type)) { return getBetweenConditionSQL(columnSQL, params[0], params[1]); } if (CoreFunctionType.IN.equals(type)) { return getInConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_IN.equals(type)) { return getNotInConditionSQL(columnSQL, params[0]); } throw new IllegalArgumentException("Core condition type not supported: " + type); } @Override public String getNotNullConditionSQL(String column) { return column + " IS NOT NULL"; } @Override public String getIsNullConditionSQL(String column) { return column + " IS NULL"; } @Override public String getIsEqualsToConditionSQL(String column, Object param) { if (param == null) { return getIsNullConditionSQL(column); } else { String paramStr = getParameterSQL(param); return column + " = " + paramStr; } } @Override public String getNotEqualsToConditionSQL(String column, Object param) { if (param == null) { return getNotNullConditionSQL(column); } else { String paramStr = getParameterSQL(param); return column + " <> " + paramStr; } } @Override public String getLikeToConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " LIKE " + paramStr; } @Override public String getGreaterThanConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " > " + paramStr; } @Override public String getGreaterOrEqualsConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " >= " + paramStr; } @Override public String getLowerThanConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " < " + paramStr; } @Override public String getLowerOrEqualsConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " <= " + paramStr; } @Override public String getBetweenConditionSQL(String column, Object from, Object to) { String fromStr = getParameterSQL(from); String toStr = getParameterSQL(to); return column + " BETWEEN " + fromStr + AND + toStr; } @Override public String getInConditionSQL(String column, Object param) { StringBuilder inStatement = new StringBuilder(); inStatement.append(column); inStatement.append(" IN ("); for (Object p : (Collection<?>) param) { inStatement.append(getParameterSQL(p) + ","); } inStatement.deleteCharAt(inStatement.length()-1); inStatement.append(")"); return inStatement.toString(); } @Override public String getNotInConditionSQL(String column, Object param) { StringBuilder inStatement = new StringBuilder(); inStatement.append(column); inStatement.append(" NOT IN ("); for (Object p : (Collection<?>) param) { inStatement.append(getParameterSQL(p) + ","); } inStatement.deleteCharAt(inStatement.length()-1); inStatement.append(")"); return inStatement.toString(); } @Override public String getParameterSQL(Object param) { if (param == null) { return "null"; } if (param instanceof Number) { return getNumberParameterSQL((Number) param); } if (param instanceof Date) { return getDateParameterSQL((Date) param); } return getStringParameterSQL(param.toString()); } @Override public String getNumberParameterSQL(Number param) { return param.toString(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); @Override public String getDateParameterSQL(Date param) { // timestamp '2015-08-24 13:14:36.615' return "TIMESTAMP '" + dateFormat.format(param) + "'"; } @Override public String getStringParameterSQL(String param) { return "'" + param + "'"; } @Override public String getLogicalConditionSQL(LogicalCondition condition) { LogicalExprType type = condition.getType(); Condition[] conditions = condition.getConditions(); if (LogicalExprType.NOT.equals(type)) { return getNotExprConditionSQL(conditions[0]); } if (LogicalExprType.AND.equals(type)) { return getAndExprConditionSQL(conditions); } if (LogicalExprType.OR.equals(type)) { return getOrExprConditionSQL(conditions); } throw new IllegalArgumentException("Logical condition type not supported: " + type); } @Override public String getNotExprConditionSQL(Condition condition) { String conditionSQL = getConditionSQL(condition); return "NOT(" + conditionSQL + ")"; } @Override public String getAndExprConditionSQL(Condition[] conditions) { return _getLogicalExprConditionSQL(conditions, "AND"); } @Override public String getOrExprConditionSQL(Condition[] conditions) { return _getLogicalExprConditionSQL(conditions, "OR"); } protected String _getLogicalExprConditionSQL(Condition[] conditions, String op) { StringBuilder out = new StringBuilder(); out.append("("); for (int i = 0; i < conditions.length; i++) { Condition condition = conditions[i]; String conditionSQL = getConditionSQL(condition); if (i > 0) { out.append(" ").append(op).append(" "); } out.append(conditionSQL); } out.append(")"); return out.toString(); } @Override public String getColumnFunctionSQL(String column, AggregateFunctionType function) { switch (function) { case SUM: { return "SUM(" + column + ")"; } case MAX: { return "MAX(" + column + ")"; } case MIN: { return "MIN(" + column + ")"; } case AVERAGE: { return "AVG(" + column + ")"; } case COUNT: { return "COUNT(" + column + ")"; } case DISTINCT: { return "COUNT(DISTINCT " + column + ")"; } default: { throw new IllegalArgumentException("Function type not valid: " + function); } } } @Override public String getCountQuerySQL(Select select) { List<SortColumn> sortColumns = new ArrayList<SortColumn>(); sortColumns.addAll(select.getOrderBys()); try { // Remove ORDER BY for better performance select.getOrderBys().clear(); return "SELECT " + getColumnFunctionSQL("*", AggregateFunctionType.COUNT) + " FROM (" + select.getSQL() + ") " + getAliasForColumnSQL("dbSQL"); } finally { select.orderBy(sortColumns); } } @Override public String getSQL(CreateTable create) { StringBuilder sql = new StringBuilder("CREATE TABLE "); List<String> pkeys = new ArrayList<String>(); String tname = getTableSQL(create); sql.append(tname); // Columns boolean first = true; sql.append(" (\n"); for (Column column : create.getColumns()) { if (!first) { sql.append(",\n"); } String name = getColumnNameSQL(column.getName()); String type = getColumnTypeSQL(column); sql.append(" ").append(name).append(" ").append(type); if (create.getPrimaryKeys().contains(column)) { sql.append(" NOT NULL"); pkeys.add(name); } first = false; } if (!create.getPrimaryKeys().isEmpty()) { sql.append(",\n"); sql.append(" PRIMARY KEY("); sql.append(StringUtils.join(pkeys, ",")); sql.append(")\n"); } sql.append(")"); return sql.toString(); } @Override public String getSQL(Select select) { // Select clause StringBuilder sql = new StringBuilder(); String selectClause = getSelectSQL(select); sql.append(selectClause); // From clause (inner SQL or table) sql.append(" ").append(getFromSQL(select)); // Where clauses List<Condition> wheres = select.getWheres(); if (!wheres.isEmpty()) { sql.append(" ").append(getWhereSQL(select)); } // Group by List<Column> groupBys = select.getGroupBys(); if (!groupBys.isEmpty()) { sql.append(" ").append(getGroupBySQL(select)); } // Order by List<SortColumn> orderBys = select.getOrderBys(); if (!orderBys.isEmpty()) { sql.append(" ").append(getOrderBySQL(select)); } // Limits int limit = select.getLimit(); int offset = select.getOffset(); if (limit > 0 || offset > 0) { String limitSql = getOffsetLimitSQL(select); if (!StringUtils.isBlank(limitSql)) { sql.append(limitSql); } } return sql.toString(); } @Override public String getSQL(Insert insert) { // Insert clause StringBuilder sql = new StringBuilder(); String insertClause = getInsertStatement(insert); sql.append(insertClause); // Table sql.append(" ").append(getTableSQL(insert)); // Columns boolean first = true; sql.append(" ("); for (Column column : insert.getColumns()) { if (!first) { sql.append(","); } String str = getColumnSQL(column); sql.append(str); first = false; } sql.append(")"); // Values first = true; sql.append(" VALUES ("); for (Object value : insert.getValues()) { if (!first) { sql.append(","); } String str = getParameterSQL(value); sql.append(str); first = false; } sql.append(")"); return sql.toString(); } @Override public String getSQL(Delete delete) { // Delete clause StringBuilder sql = new StringBuilder(); String deleteClause = getDeleteStatement(delete); sql.append(deleteClause); // From clause sql.append(" ").append(getTableSQL(delete)); // Where clauses List<Condition> wheres = delete.getWheres(); if (!wheres.isEmpty()) { sql.append(" ").append(getWhereSQL(delete)); } return sql.toString(); } @Override public String getSelectSQL(Select select) { StringBuilder clause = new StringBuilder(); clause.append(getSelectStatement(select)); clause.append(" "); if (select.getColumns().isEmpty()) { clause.append("*"); } else { boolean first = true; for (Column column : select.getColumns()) { if (!first) { clause.append(", "); } String str = getColumnSQL(column); boolean aliasNonEmpty = !StringUtils.isBlank(column.getAlias()); boolean isSimpleColumn = (column instanceof SimpleColumn) && !str.equals(getColumnNameSQL(column.getAlias())); if (aliasNonEmpty && (allowAliasInStatements() || isSimpleColumn)) { str += " " + getAliasForColumnSQL(column.getAlias()); } clause.append(str); first = false; } } return clause.toString(); } @Override public String getFromSQL(Select select) { String fromSelect = select.getFromSelect(); Table fromTable = select.getFromTable(); String from = getFromStatement(select); if (fromSelect != null) { String alias = getAliasForColumnSQL("dbSQL"); return from + " (" + fromSelect + ") " + alias; } else if (fromTable != null ){ String table = getTableSQL(select); return from + " " + table; } return ""; } @Override public String getWhereSQL(Select select) { StringBuilder sql = new StringBuilder(); List<Condition> wheres = select.getWheres(); boolean first = true; for (Condition condition : wheres) { if (first) { sql.append(getWhereStatement(select)).append(" "); } else { sql.append(AND); } String str = getConditionSQL(condition); sql.append(str); first = false; } return sql.toString(); } @Override public String getWhereSQL(Delete delete) { StringBuilder sql = new StringBuilder(); List<Condition> wheres = delete.getWheres(); boolean first = true; for (Condition condition : wheres) { if (first) { sql.append(getWhereStatement(delete)).append(" "); } else { sql.append(AND); } String str = getConditionSQL(condition); sql.append(str); first = false; } return sql.toString(); } @Override public String getGroupBySQL(Select select) { StringBuilder sql = new StringBuilder(); List<Column> groupBys = select.getGroupBys(); boolean first = true; for (Column column : groupBys) { if (first) { sql.append(getGroupByStatement(select)).append(" "); } else { sql.append(", "); } Column aliasColumn = allowAliasInStatements() ? getAliasStatement(select, column) : null; sql.append(aliasColumn != null ? getAliasForStatementSQL(aliasColumn.getAlias()) : getColumnSQL(column)); first = false; } return sql.toString(); } @Override public String getOrderBySQL(Select select) { StringBuilder sql = new StringBuilder(); List<SortColumn> orderBys = select.getOrderBys(); boolean first = true; for (SortColumn column : orderBys) { if (first) { sql.append(getOrderByStatement(select)).append(" "); } else { sql.append(", "); } Column aliasColumn = allowAliasInStatements() ? getAliasStatement(select, column.getSource()) : null; if (aliasColumn != null) { column = new SortColumn(aliasColumn, column.getOrder()); } String str = getSortColumnSQL(column); sql.append(str); first = false; } return sql.toString(); } @Override public String getOffsetLimitSQL(Select select) { int offset = select.getOffset(); int limit = select.getLimit(); StringBuilder out = new StringBuilder(); if (limit > 0) out.append(" LIMIT ").append(limit); if (offset > 0) out.append(" OFFSET ").append(offset); return out.toString(); } @Override public String getSelectStatement(Select select) { return "SELECT"; } @Override public String getInsertStatement(Insert insert) { return "INSERT INTO"; } @Override public String getDeleteStatement(Delete delete) { return "DELETE FROM"; } @Override public String getFromStatement(Select select) { return "FROM"; } @Override public String getWhereStatement(Select select) { return "WHERE"; } @Override public String getWhereStatement(Delete delete) { return "WHERE"; } @Override public String getGroupByStatement(Select select) { return "GROUP BY"; } @Override public String getOrderByStatement(Select select) { return "ORDER BY"; } // Helper methods protected Object invokeMethod(Object o, String methodName, Object[] params) { Method methods[] = o.getClass().getMethods(); for (int i = 0; i < methods.length; ++i) { if (methodName.equals(methods[i].getName())) { try { methods[i].setAccessible(true); return methods[i].invoke(o, params); } catch (IllegalAccessException ex) { return null; } catch (InvocationTargetException ite) { return null; } } } return null; } public boolean areEquals(Column column1, Column column2) { if (!column1.getName().equals(column2.getName())) { return false; } if (!column1.getClass().getName().equals(column2.getClass().getName())) { return false; } if (column1 instanceof DynamicDateColumn) { DynamicDateColumn dd1 = (DynamicDateColumn) column1; DynamicDateColumn dd2 = (DynamicDateColumn) column2; if (!dd1.getDateType().equals(dd2.getDateType())) { return false; } } if (column1 instanceof FixedDateColumn) { FixedDateColumn fd1 = (FixedDateColumn) column1; FixedDateColumn fd2 = (FixedDateColumn) column2; if (!fd1.getDateType().equals(fd2.getDateType())) { return false; } } return true; } public boolean allowAliasInStatements() { return false; } public Column getAliasStatement(Select select, Column target) { for (Column column : select.getColumns()) { if (!(column instanceof SimpleColumn) && !StringUtils.isBlank(column.getAlias()) && areEquals(column, target)) { return column; } } return null; } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5080_0
crossvul-java_data_bad_5029_0
package com.dotmarketing.cms.webforms.action; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dotcms.enterprise.PasswordFactoryProxy; import com.dotcms.repackage.nl.captcha.Captcha; import com.dotcms.repackage.org.apache.struts.Globals; import com.dotcms.repackage.org.apache.struts.action.ActionErrors; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionForward; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; import com.dotcms.repackage.org.apache.struts.action.ActionMessage; import com.dotcms.repackage.org.apache.struts.actions.DispatchAction; import com.dotcms.util.SecurityUtils; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.UserProxy; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.Role; import com.dotmarketing.business.web.HostWebAPI; import com.dotmarketing.business.web.WebAPILocator; import com.dotmarketing.cms.factories.PublicAddressFactory; import com.dotmarketing.cms.factories.PublicCompanyFactory; import com.dotmarketing.cms.factories.PublicEncryptionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.factories.ClickstreamFactory; import com.dotmarketing.factories.EmailFactory; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.portlets.categories.model.Category; import com.dotmarketing.portlets.user.factories.UserCommentsFactory; import com.dotmarketing.portlets.user.model.UserComment; import com.dotmarketing.portlets.webforms.model.WebForm; import com.dotmarketing.util.Config; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.model.Address; import com.liferay.portal.model.Company; import com.liferay.portal.model.User; import com.liferay.util.servlet.UploadServletRequest; /** * * @author David * @version $Revision: 1.5 $ $Date: 2007/07/18 16:48:42 $ */ public final class SubmitWebFormAction extends DispatchAction { HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI(); @SuppressWarnings("unchecked") public ActionForward unspecified(ActionMapping rMapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); //Email parameters HttpSession session = request.getSession(); Host currentHost = hostWebAPI.getCurrentHost(request); User currentUser = (User) session.getAttribute(WebKeys.CMS_USER); String method = request.getMethod(); String errorURL = request.getParameter("errorURL"); errorURL = (!UtilMethods.isSet(errorURL) ? request.getHeader("referer") : errorURL); if(errorURL.indexOf("?") > -1) { errorURL = errorURL.substring(0,errorURL.lastIndexOf("?")); } String x = request.getRequestURI(); if(request.getParameterMap().size() <2){ return null; } //Checking for captcha boolean useCaptcha = Config.getBooleanProperty("FORCE_CAPTCHA",true); if(!useCaptcha){ useCaptcha = new Boolean(request.getParameter("useCaptcha")).booleanValue(); } String captcha = request.getParameter("captcha"); if (useCaptcha) { Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME); String captchaSession=captchaObj!=null ? captchaObj.getAnswer() : null; if(captcha ==null && Config.getBooleanProperty("FORCE_CAPTCHA",true)){ response.getWriter().write("Captcha is required to submit this form ( FORCE_CAPTCHA=true ).<br>To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false"); return null; } if(!UtilMethods.isSet(captcha) || !UtilMethods.isSet(captchaSession) || !captcha.equals(captchaSession)) { errors.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", "Validation Image")); request.setAttribute(Globals.ERROR_KEY, errors); session.setAttribute(Globals.ERROR_KEY, errors); String queryString = request.getQueryString(); String invalidCaptchaURL = request.getParameter("invalidCaptchaReturnUrl"); if(!UtilMethods.isSet(invalidCaptchaURL)) { invalidCaptchaURL = errorURL; } ActionForward af = new ActionForward(); af.setRedirect(true); if (UtilMethods.isSet(queryString)) { af.setPath(invalidCaptchaURL + "?" + queryString + "&error=Validation-Image"); } else { af.setPath(invalidCaptchaURL + "?error=Validation-Image"); } return af; } } Map<String, Object> parameters = null; if (request instanceof UploadServletRequest) { UploadServletRequest uploadReq = (UploadServletRequest) request; parameters = new HashMap<String, Object> (uploadReq.getParameterMap()); for (Entry<String, Object> entry : parameters.entrySet()) { if(entry.getKey().toLowerCase().indexOf("file") > -1 && !entry.getKey().equals("attachFiles")) { parameters.put(entry.getKey(), uploadReq.getFile(entry.getKey())); } } } else { parameters = new HashMap<String, Object> (request.getParameterMap()); } Set<String> toValidate = new java.util.HashSet<String>(parameters.keySet()); //Enhancing the ignored parameters not to be send in the email String ignoredParameters = (String) EmailFactory.getMapValue("ignore", parameters); if(ignoredParameters == null) { ignoredParameters = ""; } ignoredParameters += ":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:"; parameters.put("ignore", ignoredParameters); // getting categories from inodes // getting parent category name and child categories name // and replacing the "categories" parameter String categories = ""; String[] categoriesArray = request.getParameterValues("categories"); if (categoriesArray != null) { HashMap hashCategories = new HashMap<String, String>(); for (int i = 0; i < categoriesArray.length; i++) { Category node = (Category) InodeFactory.getInode(categoriesArray[i], Category.class); Category parent = (Category) InodeFactory.getParentOfClass(node, Category.class); String parentCategoryName = parent.getCategoryName(); if (hashCategories.containsKey(parentCategoryName)) { String childCategoryName = (String) hashCategories.get(parentCategoryName); if (UtilMethods.isSet(childCategoryName)) { childCategoryName += ", "; } childCategoryName += node.getCategoryName(); hashCategories.put(parentCategoryName, childCategoryName); } else { hashCategories.put(parentCategoryName, node.getCategoryName()); } } Set<String> keySet = hashCategories.keySet(); for (String stringKey: keySet) { if (UtilMethods.isSet(categories)) { categories += "; "; } categories += stringKey + " : " + (String) hashCategories.get(stringKey); parameters.put(stringKey, (String) hashCategories.get(stringKey)); } parameters.remove("categories"); } WebForm webForm = new WebForm(); try { /*validation parameter should ignore the returnUrl and erroURL field in the spam check*/ String[] removeParams = ignoredParameters.split(":"); for(String param : removeParams){ toValidate.remove(param); } parameters.put("request", request); parameters.put("response", response); //Sending the email webForm = EmailFactory.sendParameterizedEmail(parameters, toValidate, currentHost, currentUser); webForm.setCategories(categories); if(UtilMethods.isSet(request.getParameter("createAccount")) && request.getParameter("createAccount").equals("true")) { //if we create account set to true we create a user account and add user comments. createAccount(webForm, request); try{ String userInode = webForm.getUserInode(); String customFields = webForm.getCustomFields(); customFields += " User Inode = " + String.valueOf(userInode) + " | "; webForm.setCustomFields(customFields); } catch(Exception e){ } } if(UtilMethods.isSet(webForm.getFormType())){ HibernateUtil.saveOrUpdate(webForm); } if (request.getParameter("return") != null) { ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("return"))); af.setRedirect(true); return af; } else if (request.getParameter("returnUrl") != null) { ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("returnUrl"))); af.setRedirect(true); return af; } else { return rMapping.findForward("thankYouPage"); } } catch (DotRuntimeException e) { errors.add(Globals.ERROR_KEY, new ActionMessage("error.processing.your.email")); request.getSession().setAttribute(Globals.ERROR_KEY, errors); String queryString = request.getQueryString(); if (queryString == null) { java.util.Enumeration<String> parameterNames = request.getParameterNames(); queryString = ""; String parameterName; for (; parameterNames.hasMoreElements();) { parameterName = parameterNames.nextElement(); if (0 < queryString.length()) { queryString = queryString + "&" + parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName)); } else { queryString = parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName)); } } } ActionForward af; if (UtilMethods.isSet(queryString)) { af = new ActionForward(SecurityUtils.stripReferer(request, errorURL + "?" + queryString)); } else { af = new ActionForward(SecurityUtils.stripReferer(request, errorURL)); } af.setRedirect(true); return af; } } private void createAccount(WebForm form, HttpServletRequest request) throws Exception { User user = APILocator.getUserAPI().loadByUserByEmail(form.getEmail(), APILocator.getUserAPI().getSystemUser(), false); User defaultUser = APILocator.getUserAPI().getDefaultUser(); Date today = new Date(); if (user.isNew() || (!user.isNew() && user.getLastLoginDate() == null)) { // ### CREATE USER ### Company company = PublicCompanyFactory.getDefaultCompany(); user.setEmailAddress(form.getEmail().trim().toLowerCase()); user.setFirstName(form.getFirstName() == null ? "" : form.getFirstName()); user.setMiddleName(form.getMiddleName() == null ? "" : form.getMiddleName()); user.setLastName(form.getLastName() == null ? "" : form.getLastName()); user.setNickName(""); user.setCompanyId(company.getCompanyId()); user.setGreeting("Welcome, " + user.getFullName() + "!"); // Set defaults values if (user.isNew()) { //if it's a new user we set random password String pass = PublicEncryptionFactory.getRandomPassword(); // Use new password hash method user.setPassword(PasswordFactoryProxy.generateHash(pass)); user.setLanguageId(defaultUser.getLanguageId()); user.setTimeZoneId(defaultUser.getTimeZoneId()); user.setSkinId(defaultUser.getSkinId()); user.setDottedSkins(defaultUser.isDottedSkins()); user.setRoundedSkins(defaultUser.isRoundedSkins()); user.setResolution(defaultUser.getResolution()); user.setRefreshRate(defaultUser.getRefreshRate()); user.setLayoutIds(""); user.setActive(true); user.setCreateDate(today); } APILocator.getUserAPI().save(user,APILocator.getUserAPI().getSystemUser(),false); // ### END CREATE USER ### // ### CREATE USER_PROXY ### UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user.getUserId(),APILocator.getUserAPI().getSystemUser(), false); userProxy.setPrefix(""); userProxy.setTitle(form.getTitle()); userProxy.setOrganization(form.getOrganization()); userProxy.setUserId(user.getUserId()); com.dotmarketing.business.APILocator.getUserProxyAPI().saveUserProxy(userProxy,APILocator.getUserAPI().getSystemUser(), false); // ### END CRETE USER_PROXY ### // saving user inode on web form form.setUserInode(userProxy.getInode()); if(UtilMethods.isSet(form.getFormType())){ HibernateUtil.saveOrUpdate(form); } ///// WE CAN DO THIS! BUT WE NEED TO ADD CATEGORIES TO WEBFORM AND ALSO CHANGE THE PROCESSES THAT //// CREATE THE EXCEL DOWNLOAD FROM WEB FORMS. I DIDN'T ADD IT SO I COMMENTED THIS CODE FOR NOW //get the old categories, wipe them out /* List<Category> categories = InodeFactory.getParentsOfClass(userProxy, Category.class); for (int i = 0; i < categories.size(); i++) { categories.get(i).deleteChild(userProxy); } */ // Save the new categories /*String[] arr = form.getCategories(); if (arr != null) { for (int i = 0; i < arr.length; i++) { Category node = (Category) InodeFactory.getInode(arr[i], Category.class); node.addChild(userProxy); } }*/ // ### CREATE ADDRESS ### try { List<Address> addresses = PublicAddressFactory.getAddressesByUserId(user.getUserId()); Address address = (addresses.size() > 0 ? addresses.get(0) : PublicAddressFactory.getInstance()); address.setStreet1(form.getAddress1() == null ? "" : form.getAddress1()); address.setStreet2(form.getAddress2() == null ? "" : form.getAddress2()); address.setCity(form.getCity() == null ? "" : form.getCity()); address.setState(form.getState() == null ? "" : form.getState()); address.setZip(form.getZip() == null ? "" : form.getZip()); String phone = form.getPhone(); address.setPhone(phone == null ? "" : phone); address.setUserId(user.getUserId()); address.setCompanyId(company.getCompanyId()); PublicAddressFactory.save(address); } catch (Exception ex) { Logger.error(this,ex.getMessage(),ex); } Role defaultRole = com.dotmarketing.business.APILocator.getRoleAPI().loadRoleByKey(Config.getStringProperty("CMS_VIEWER_ROLE")); String roleId = defaultRole.getId(); if (InodeUtils.isSet(roleId)) { com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user); } } // ### END CREATE ADDRESS ### // ### BUILD THE USER COMMENT ### addUserComments(user.getUserId(),form,request); // ### END BUILD THE USER COMMENT ### /* associate user with their clickstream request */ if(Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)){ ClickstreamFactory.setClickStreamUser(user.getUserId(), request); } } private void addUserComments(String userid, WebForm webForm, HttpServletRequest request) throws Exception { Date now = new Date(); String webFormType = webForm.getFormType(); String webFormId = webForm.getWebFormId(); UserComment userComments = new UserComment(); userComments.setUserId(userid); userComments.setCommentUserId(userid); userComments.setDate(now); if (request.getParameter("comments")!=null) { userComments.setComment(request.getParameter("comments")); } else if(UtilMethods.isSet(webForm.getFormType())) { userComments.setSubject("User submitted: " + webFormType); userComments.setComment("Web Form: " + webFormType + " - ID: " + webFormId); } else{ userComments.setSubject("User submitted Form: Open Entry "); StringBuffer buffy = new StringBuffer(); Enumeration x = request.getParameterNames(); while(x.hasMoreElements()){ String key = (String) x.nextElement(); buffy.append(key); buffy.append(":\t"); buffy.append(request.getParameter(key)); buffy.append("\n"); if(buffy.length() > 65000){ break; } } userComments.setComment(buffy.toString()); } userComments.setTypeComment(UserComment.TYPE_INCOMING); userComments.setMethod(UserComment.METHOD_WEB); userComments.setCommunicationId(null); UserCommentsFactory.saveUserComment(userComments); } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5029_0
crossvul-java_data_good_5080_1
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.dataprovider.sql; import org.dashbuilder.dataset.DataSet; import org.dashbuilder.dataset.DataSetGroupTest; import org.dashbuilder.dataset.DataSetLookupFactory; import org.dashbuilder.dataset.filter.FilterFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import static org.dashbuilder.dataset.ExpenseReportsData.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class SQLInjectionAttacksTest extends SQLDataSetTestBase { @Mock Logger logger; @Before public void setUp() throws Exception{ super.setUp(); sqlDataSetProvider.log = logger; doAnswer(invocationOnMock -> { String sql = (String) invocationOnMock.getArguments()[0]; System.out.println(sql); return null; }).when(logger).debug(anyString()); } @Override public void testAll() throws Exception { testStringFilterInjection(); } public void testStringFilterInjection() throws Exception { DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David' OR EMPLOYEE != 'Toni")) .buildLookup()); assertEquals(result.getRowCount(), 0); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David\" OR EMPLOYEE != \"Toni")) .buildLookup()); assertEquals(result.getRowCount(), 0); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David` OR EMPLOYEE != `Toni")) .buildLookup()); assertEquals(result.getRowCount(), 0); } @Test public void testDropTable() throws Exception { DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(COLUMN_EMPLOYEE, FilterFactory.equalsTo("David'; DROP TABLE 'EXPENSE_REPORTS; SELECT 'a' = 'a")) .buildLookup()); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .buildLookup()); assertEquals(result.getRowCount(), 50); } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5080_1
crossvul-java_data_good_5220_1
/* * Copyright 2013-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.jpa.domain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.PluralAttribute; import org.springframework.data.domain.Sort; import org.springframework.util.Assert; /** * Sort option for queries that wraps JPA meta-model {@link Attribute}s for sorting. * * @author Thomas Darimont * @author Oliver Gierke * @author Christoph Strobl */ public class JpaSort extends Sort { private static final long serialVersionUID = 1L; /** * Creates a new {@link JpaSort} for the given attributes with the default sort direction. * * @param attributes must not be {@literal null} or empty. */ public JpaSort(Attribute<?, ?>... attributes) { this(DEFAULT_DIRECTION, attributes); } /** * Creates a new {@link JpaSort} instance with the given {@link Path}s. * * @param paths must not be {@literal null} or empty. */ public JpaSort(JpaSort.Path<?, ?>... paths) { this(DEFAULT_DIRECTION, paths); } /** * Creates a new {@link JpaSort} for the given direction and attributes. * * @param direction the sorting direction. * @param attributes must not be {@literal null} or empty. */ public JpaSort(Direction direction, Attribute<?, ?>... attributes) { this(direction, paths(attributes)); } /** * Creates a new {@link JpaSort} for the given direction and {@link Path}s. * * @param direction the sorting direction. * @param paths must not be {@literal null} or empty. */ public JpaSort(Direction direction, Path<?, ?>... paths) { this(direction, Arrays.asList(paths)); } private JpaSort(Direction direction, List<Path<?, ?>> paths) { this(Collections.<Order> emptyList(), direction, paths); } private JpaSort(List<Order> orders, Direction direction, List<Path<?, ?>> paths) { super(combine(orders, direction, paths)); } private JpaSort(List<Order> orders) { super(orders); } /** * Returns a new {@link JpaSort} with the given sorting criteria added to the current one. * * @param direction can be {@literal null}. * @param attributes must not be {@literal null}. * @return */ public JpaSort and(Direction direction, Attribute<?, ?>... attributes) { Assert.notNull(attributes, "Attributes must not be null!"); return and(direction, paths(attributes)); } /** * Returns a new {@link JpaSort} with the given sorting criteria added to the current one. * * @param direction can be {@literal null}. * @param paths must not be {@literal null}. * @return */ public JpaSort and(Direction direction, Path<?, ?>... paths) { Assert.notNull(paths, "Paths must not be null!"); List<Order> existing = new ArrayList<Order>(); for (Order order : this) { existing.add(order); } return new JpaSort(existing, direction, Arrays.asList(paths)); } /** * Returns a new {@link JpaSort} with the given sorting criteria added to the current one. * * @param direction can be {@literal null}. * @param properties must not be {@literal null} or empty. * @return */ public JpaSort andUnsafe(Direction direction, String... properties) { Assert.notEmpty(properties, "Properties must not be null!"); List<Order> orders = new ArrayList<Order>(); for (Order order : this) { orders.add(order); } for (String property : properties) { orders.add(new JpaOrder(direction, property)); } return new JpaSort(orders, direction, Collections.<Path<?, ?>> emptyList()); } /** * Turns the given {@link Attribute}s into {@link Path}s. * * @param attributes must not be {@literal null} or empty. * @return */ private static Path<?, ?>[] paths(Attribute<?, ?>[] attributes) { Assert.notNull(attributes, "Attributes must not be null!"); Assert.isTrue(attributes.length > 0, "Attributes must not be empty"); Path<?, ?>[] paths = new Path[attributes.length]; for (int i = 0; i < attributes.length; i++) { paths[i] = path(attributes[i]); } return paths; } private static List<Order> combine(List<Order> orders, Direction direction, List<Path<?, ?>> paths) { List<Order> result = new ArrayList<Sort.Order>(orders); for (Path<?, ?> path : paths) { result.add(new Order(direction, path.toString())); } return result; } /** * Creates a new {@link Path} for the given {@link Attribute}. * * @param attribute must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") public static <A extends Attribute<T, S>, T, S> Path<T, S> path(A attribute) { Assert.notNull(attribute, "Attribute must not be null!"); return new Path<T, S>(Arrays.asList(attribute)); } /** * Creates a new {@link Path} for the given {@link PluralAttribute}. * * @param attribute must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") public static <P extends PluralAttribute<T, ?, S>, T, S> Path<T, S> path(P attribute) { Assert.notNull(attribute, "Attribute must not be null!"); return new Path<T, S>(Arrays.asList(attribute)); } /** * Creates new unsafe {@link JpaSort} based on given properties. * * @param properties must not be {@literal null} or empty. * @return */ public static JpaSort unsafe(String... properties) { return unsafe(Sort.DEFAULT_DIRECTION, properties); } /** * Creates new unsafe {@link JpaSort} based on given {@link Direction} and properties. * * @param direction must not be {@literal null}. * @param properties must not be {@literal null} or empty. * @return */ public static JpaSort unsafe(Direction direction, String... properties) { Assert.notNull(direction, "Direction must not be null!"); Assert.notEmpty(properties, "Properties must not be empty!"); Assert.noNullElements(properties, "Properties must not contain null values!"); return unsafe(direction, Arrays.asList(properties)); } /** * Creates new unsafe {@link JpaSort} based on given {@link Direction} and properties. * * @param direction must not be {@literal null}. * @param properties must not be {@literal null} or empty. * @return */ public static JpaSort unsafe(Direction direction, List<String> properties) { Assert.notEmpty(properties, "Properties must not be empty!"); List<Order> orders = new ArrayList<Order>(); for (String property : properties) { orders.add(new JpaOrder(direction, property)); } return new JpaSort(orders); } /** * Value object to abstract a collection of {@link Attribute}s. * * @author Oliver Gierke */ public static class Path<T, S> { private final Collection<Attribute<?, ?>> attributes; private Path(List<? extends Attribute<?, ?>> attributes) { this.attributes = Collections.unmodifiableList(attributes); } /** * Collects the given {@link Attribute} and returning a new {@link Path} pointing to the attribute type. * * @param attribute must not be {@literal null}. * @return */ public <A extends Attribute<S, U>, U> Path<S, U> dot(A attribute) { return new Path<S, U>(add(attribute)); } /** * Collects the given {@link PluralAttribute} and returning a new {@link Path} pointing to the attribute type. * * @param attribute must not be {@literal null}. * @return */ public <P extends PluralAttribute<S, ?, U>, U> Path<S, U> dot(P attribute) { return new Path<S, U>(add(attribute)); } private List<Attribute<?, ?>> add(Attribute<?, ?> attribute) { Assert.notNull(attribute, "Attribute must not be null!"); List<Attribute<?, ?>> newAttributes = new ArrayList<Attribute<?, ?>>(attributes.size() + 1); newAttributes.addAll(attributes); newAttributes.add(attribute); return newAttributes; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Attribute<?, ?> attribute : attributes) { builder.append(attribute.getName()).append("."); } return builder.length() == 0 ? "" : builder.substring(0, builder.lastIndexOf(".")); } } /** * @author Christoph Strobl */ public static class JpaOrder extends Order { private final boolean unsafe; private final boolean ignoreCase; /** * Creates a new {@link JpaOrder} instance. if order is {@literal null} then order defaults to * {@link Sort#DEFAULT_DIRECTION} * * @param direction can be {@literal null}, will default to {@link Sort#DEFAULT_DIRECTION}. * @param property must not be {@literal null}. */ private JpaOrder(Direction direction, String property) { this(direction, property, NullHandling.NATIVE); } /** * Creates a new {@link Order} instance. if order is {@literal null} then order defaults to * {@link Sort#DEFAULT_DIRECTION}. * * @param direction can be {@literal null}, will default to {@link Sort#DEFAULT_DIRECTION}. * @param property must not be {@literal null}. * @param nullHandlingHint can be {@literal null}, will default to {@link NullHandling#NATIVE}. */ private JpaOrder(Direction direction, String property, NullHandling nullHandlingHint) { this(direction, property, nullHandlingHint, false, true); } private JpaOrder(Direction direction, String property, NullHandling nullHandling, boolean ignoreCase, boolean unsafe) { super(direction, property, nullHandling); this.ignoreCase = ignoreCase; this.unsafe = unsafe; } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#with(org.springframework.data.domain.Sort.Direction) */ @Override public JpaOrder with(Direction order) { return new JpaOrder(order, getProperty(), getNullHandling(), isIgnoreCase(), this.unsafe); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#with(org.springframework.data.domain.Sort.NullHandling) */ @Override public JpaOrder with(NullHandling nullHandling) { return new JpaOrder(getDirection(), getProperty(), nullHandling, isIgnoreCase(), this.unsafe); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#nullsFirst() */ @Override public JpaOrder nullsFirst() { return with(NullHandling.NULLS_FIRST); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#nullsLast() */ @Override public JpaOrder nullsLast() { return with(NullHandling.NULLS_LAST); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#nullsNative() */ public JpaOrder nullsNative() { return with(NullHandling.NATIVE); } /** * Creates new {@link Sort} with potentially unsafe {@link Order} instances. * * @param properties must not be {@literal null}. * @return */ public Sort withUnsafe(String... properties) { Assert.notEmpty(properties, "Properties must not be empty!"); Assert.noNullElements(properties, "Properties must not contain null values!"); List<Order> orders = new ArrayList<Order>(); for (String property : properties) { orders.add(new JpaOrder(getDirection(), property, getNullHandling(), isIgnoreCase(), this.unsafe)); } return new Sort(orders); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#ignoreCase() */ @Override public JpaOrder ignoreCase() { return new JpaOrder(getDirection(), getProperty(), getNullHandling(), true, this.unsafe); } /* * (non-Javadoc) * @see org.springframework.data.domain.Sort.Order#isIgnoreCase() */ @Override public boolean isIgnoreCase() { return super.isIgnoreCase() || ignoreCase; } /** * @return true if {@link JpaOrder} created {@link #withUnsafe(String...)}. */ public boolean isUnsafe() { return unsafe; } } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5220_1
crossvul-java_data_good_5029_1
package com.dotmarketing.factories; //import com.dotmarketing.threads.DeliverNewsletterThread; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import org.apache.velocity.Template; import org.apache.velocity.context.Context; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.UserProxy; import com.dotmarketing.business.APILocator; import com.dotmarketing.cms.factories.PublicAddressFactory; import com.dotmarketing.cms.factories.PublicCompanyFactory; import com.dotmarketing.cms.factories.PublicEncryptionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.exception.WebAssetException; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.fileassets.business.FileAssetAPI; import com.dotmarketing.portlets.files.business.FileAPI; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory; import com.dotmarketing.portlets.mailinglists.model.MailingList; import com.dotmarketing.portlets.webforms.model.WebForm; import com.dotmarketing.util.Config; import com.dotmarketing.util.FormSpamFilter; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.Mailer; import com.dotmarketing.util.Parameter; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.language.LanguageException; import com.liferay.portal.language.LanguageUtil; import com.liferay.portal.model.Address; import com.liferay.portal.model.Company; import com.liferay.portal.model.User; import com.liferay.util.FileUtil; /** * DOCUMENT ME! * * @author $author$ * @version $Revision: 1.10 $ */ public class EmailFactory { private static Long emailTime = new Long(System.currentTimeMillis()); /** * Rewrites urls to point back to the redirection servlet to track links * and then calls the alterBodyHtmlAbsolutizePaths method */ public static StringBuffer alterBodyHTML(StringBuffer HTML, String serverName) { return new StringBuffer(alterBodyHTML(HTML.toString(), serverName)); } public static String alterBodyHTML(String HTML, String serverName) { //This is the new Regular Expression for white spaces ([ .\r\n&&[^>]]*) // Replacing links "a href" like tags axcluding the mail to links HTML = HTML.replaceAll("(?i)(?s)<a[^>]+href=\"([^/(http://)(https://)(#)(mailto:\")])(.*)\"[^>]*>", "<a href=\"http://$1$2\">"); HTML = HTML.replaceAll( //"(?i)(?s)<a[^>]+href=\"([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>", "(?i)(?s)<a href=\"([^#])([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>", "<a href=\"http://" + serverName //+ "/redirect?r=<rId>&redir=$1\">$2</a>") + "/redirect?r=<rId>&redir=$1$2\">$3</a>") .replaceAll("<a href=\"http://" + serverName + "/redirect\\?r=<rId>&redir=(mailto:[^\"]+)\">", "<a href=\"$1\">"); HTML = alterBodyHtmlAbsolutizePaths(HTML, serverName); return HTML; } /** * Change all the relative paths in the email body to absolute paths */ public static StringBuffer alterBodyHtmlAbsolutizePaths(StringBuffer HTML, String serverName) { return new StringBuffer(alterBodyHtmlAbsolutizePaths(HTML.toString(), serverName)); } public static String alterBodyHtmlAbsolutizePaths(String HTML, String serverName) { String message = HTML; //Replacing links "TD background" like tags message = message .replaceAll( "<\\s*td([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<td$1background=\"http://" + serverName + "$2\"$3>"); // Replacing links "TR background" like tags message = message .replaceAll( "<\\s*tr([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<tr$1background=\"http://" + serverName + "$2\"$3>"); // Replacing links "IMG SRC" like tags message = message.replaceAll( "<\\s*img([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<img$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "A HREF" like tags message = message .replaceAll( "<\\s*link([^>]*)href\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<link$1href=\"http://" + serverName + "$2\"$3>"); // Replacing links "SCRIPT" like tags message = message .replaceAll( "<\\s*script([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<script$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "APPLET" with codebase like tags message = message .replaceAll( "<\\s*applet([^>]*)codebase\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<applet$1codebase=\"http://" + serverName + "$2\"$3>"); // Replacing links "APPLET" without codebase like tags message = message .replaceAll( "<\\s*applet(([^>][^(codebase)])*)code\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?(([^>][^(codebase)])*)>", "<applet$1code=\"http://" + serverName + "$4\"$5>"); // Replacing links "IFRAME" src replacement message = message .replaceAll( "<\\s*iframe([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<iframe$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "IFRAME" longdesc replacement message = message .replaceAll( "<\\s*iframe([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<iframe$1longdesc=\"http://" + serverName + "$2\"$3>"); // Replacing links "FRAME" src replacement message = message .replaceAll( "<\\s*frame([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<frame$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "FRAME" longdesc replacement message = message .replaceAll( "<\\s*frame([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<frame$1longdesc=\"http://" + serverName + "$2\"$3>"); // Replacing some style URLs message = message .replaceAll( "<([^>]*)style\\s*=\\s*[\"\']?([^\'\">]*)url\\s*\\(\\s*([^>]*)\\s*\\)([^\'\">]*)[\"\']?([^>]*)>", "<$1style=\"$2url(http://" + serverName + "$3)$4\"$5>"); // Fixing absolute paths message = message.replaceAll("http://" + serverName + "\\s*http://", "http://"); return message; } /** * Sends the forgot password email with the new random generated password * @throws DotSecurityException * @throws DotDataException */ public static boolean sendForgotPassword(User user, String newPassword, String hostId) throws DotDataException, DotSecurityException { HostAPI hostAPI = APILocator.getHostAPI(); // build a decent default context Context context = VelocityUtil.getBasicContext(); context.put("user", user); context.put("UtilMethods", new UtilMethods()); context.put("language", Long.toString(APILocator.getLanguageAPI().getDefaultLanguage().getId())); context.put("password", newPassword); Host host = hostAPI.find(hostId, user, true); context.put("host", host); StringWriter writer = new StringWriter(); String idInode = APILocator.getIdentifierAPI().find(host, Config .getStringProperty("PATH_FORGOT_PASSWORD_EMAIL")).getInode(); String languageStr = "_" + APILocator.getLanguageAPI().getDefaultLanguage().getId(); try { String message = ""; try { Template t = UtilMethods.getVelocityTemplate("live/"+ idInode+ languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); t.merge(context, writer); Logger .debug(EmailFactory.class, "writer:" + writer.getBuffer()); message = writer.toString().trim(); } catch (ResourceNotFoundException ex) { message = "<center><b>And error has ocurred loading de message's page<b></center>"; } Mailer m = new Mailer(); m.setToEmail(user.getEmailAddress()); m.setSubject("Your " + host.getHostname() + " Password"); m.setHTMLBody(message); m.setFromEmail(Config.getStringProperty("EMAIL_SYSTEM_ADDRESS")); return m.sendMessage(); } catch (Exception e) { Logger.warn(EmailFactory.class, e.toString(), e); return false; } } public static boolean isSubscribed(MailingList list, User s){ UserProxy up; try { up = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(s,APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error(EmailFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return MailingListFactory.isSubscribed(list, up); } /** * * Send emails based on the parameters given to the method, basically is used * to send emails based on parameters received html forms but it can be used * to send emails using parameters that come form any source * * Some parameters are required and need to be passed in order the method to work * correctly, here it is the description of the predefined parameters and when they are * required or not: * * formType/formName: The name of the form used to generate the reports and to save the files submitted * as parameters, so if no formType or formName is supplied then no report * or files will be saved. * to: Email address where the email will be sent * from: Email address will be used as the from address * subject: Subject of the email * cc: Carbon copy of the email * bcc: Hidden carbon copy of the email * html: Set it to false|0|f if you don't want to send an html kind of email * dispatch: Not used reserved for struts processing * order: Order how you want to present the parameters, the valid syntax of this * parameter is like: param1,param2,... * prettyOrder: This property goes together with the order property to specify * prettiest names to the parameters, these prettiest names are used * when building the simple html table e-mail * ignore: Parameters you want to exclude from the email sent, the valid syntax of this * parameter is like ;param1;param2;..., this is only used when building the * simple html table email body and not when building the email from a given template * emailTemplate: The path to the email template to be used to generate the email * it can be a path in the dotCMS tree or a real path in the server file system * under /liferay folder, dotCMS paths take precedence over filesystem paths * attachFiles: A comma separated list of the file kind of fields you want the method include as * attachments to the email to send * If the following parameters are included an auto reply message will be send * to the from email * autoReplyFrom: Address to be used as the from * autoReplySubject: Subject of the message * autoReplyText: Message to send * autoReplyTemplate: A path to an html template that can be used to generate this message * it can be a path in the dotCMS tree or a real path in the server file system * under /liferay folder * * @param parameters A map of the submitted fields, any kind of parameter can * be used and will be passed to the email template to render the email body text used when * sending the email but only string or file kind parameters will be used to generate the database * reports and generate plain table html table like body text when no html template is passed * in the parameters * * @param spamValidation List of fields that wants to be checked for possible spam * @param otherIgnoredParams A list of other fields (more than the default ones) that you want to * be excluded from the list of fields to be sent in the email * @param host Current dotCMS host used to submit the form * @param user User how submits the form (can be null then the user parameters won't be excluded * on the template substitution) * @return The saved webform if a formType/formName parameter is specified if not returns null. * @throws DotRuntimeException when spam is detected or any other mayor error occurs * CreditCardDeniedException when the credit card gets denied */ public static WebForm sendParameterizedEmail(Map<String,Object> parameters, Set<String> spamValidation, Host host, User user) throws DotRuntimeException { // check for possible spam if(spamValidation != null) if (FormSpamFilter.isSpamRequest(parameters, spamValidation)) { throw new DotRuntimeException("Spam detected"); } //Variables initialization //Default parameters to be ignored when sending the email String ignoreString = ":formType:formName:to:from:subject:cc:bcc:html:dispatch:order:" + "prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:" + "ignore:emailTemplate:autoReplyTemplate:autoReplyHtml:chargeCreditCard:attachFiles:"; if(UtilMethods.isSet(getMapValue("ignore", parameters))) { ignoreString += getMapValue("ignore", parameters).toString().replace(",", ":") + ":"; } // Sort the forms' fields by the given order parameter String order = (String)getMapValue("order", parameters); Map<String, Object> orderedMap = new LinkedHashMap<String, Object>(); // Parameter prettyOrder is used to map // the pretty names of the variables used in the order field // E.G: order = firstName, lastName // prettyOrder = First Name, Last Name String prettyOrder = (String)getMapValue("prettyOrder", parameters); Map<String, String> prettyVariableNamesMap = new LinkedHashMap<String, String>(); // Parameter attachFiles is used to specify the file kind of fields you want to attach // to the mail is sent by this method // E.G: attachFiles = file1, file2, ... String attachFiles = (String)getMapValue("attachFiles", parameters); //Building the parameters maps from the order and pretty order parameters if (order != null) { String[] orderArr = order.split("[;,]"); String[] prettyOrderArr = prettyOrder!=null?prettyOrder.split("[;,]"):new String[0]; for (int i = 0; i < orderArr.length; i++) { String orderParam = orderArr[i].trim(); Object value = (getMapValue(orderParam, parameters) == null) ? null : getMapValue(orderParam, parameters); if(value != null) { //if pretty name is passed using it as a key value in the ordered map if (prettyOrderArr.length > i) prettyVariableNamesMap.put(orderArr[i].trim(), prettyOrderArr[i].trim()); else prettyVariableNamesMap.put(orderArr[i].trim(), orderArr[i].trim()); orderedMap.put(orderArr[i].trim(), value); } } } for (Entry<String, Object> param : parameters.entrySet()) { if(!orderedMap.containsKey(param.getKey())) { orderedMap.put(param.getKey(), param.getValue()); prettyVariableNamesMap.put(param.getKey(), param.getKey()); } } StringBuffer filesLinks = new StringBuffer(); // Saving the form in the database and the submitted file to the dotCMS String formType = getMapValue("formType", parameters) != null? (String)getMapValue("formType", parameters):(String)getMapValue("formName", parameters); WebForm formBean = saveFormBean(parameters, host, formType, ignoreString, filesLinks); // Setting up the email // Email variables - decrypting crypted email addresses String from = UtilMethods.replace((String)getMapValue("from", parameters), "spamx", ""); String to = UtilMethods.replace((String)getMapValue("to", parameters), "spamx", ""); String cc = UtilMethods.replace((String)getMapValue("cc", parameters), "spamx", ""); String bcc = UtilMethods.replace((String)getMapValue("bcc", parameters), "spamx", ""); String fromName = UtilMethods.replace((String)getMapValue("fromName", parameters), "spamx", ""); try { from = PublicEncryptionFactory.decryptString(from); } catch (Exception e) { } try { to = PublicEncryptionFactory.decryptString(to); } catch (Exception e) { } try { cc = PublicEncryptionFactory.decryptString(cc); } catch (Exception e) { } try { bcc = PublicEncryptionFactory.decryptString(bcc); } catch (Exception e) { } try { fromName = PublicEncryptionFactory.decryptString(fromName); } catch (Exception e) { } String subject = (String)getMapValue("subject", parameters); subject = (subject == null) ? "Mail from " + host.getHostname() + "" : subject; // strip line breaks from headers from = from.replaceAll("\\s", " "); to = to.replaceAll("\\s", " "); cc = cc.replaceAll("\\s", " "); bcc = bcc.replaceAll("\\s", " "); fromName = fromName.replaceAll("\\s", " "); subject = subject.replaceAll("\\s", " "); String emailFolder = (String)getMapValue("emailFolder", parameters); boolean html = getMapValue("html", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("html", parameters)):true; String templatePath = (String) getMapValue("emailTemplate", parameters); // Building email message no template Map<String, String> emailBodies = null; try { emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user); } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: Couldn't build the email body text.", e); throw new DotRuntimeException("sendForm: Couldn't build the email body text.", e); } // Saving email backup in a file try { String filePath = FileUtil.getRealPath(Config.getStringProperty("EMAIL_BACKUPS")); new File(filePath).mkdir(); File file = null; synchronized (emailTime) { emailTime = new Long(emailTime.longValue() + 1); if (UtilMethods.isSet(emailFolder)) { new File(filePath + File.separator + emailFolder).mkdir(); filePath = filePath + File.separator + emailFolder; } file = new File(filePath + File.separator + emailTime.toString() + ".html"); } if (file != null) { java.io.OutputStream os = new java.io.FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os); if(emailBodies.get("emailHTMLBody") != null) bos.write(emailBodies.get("emailHTMLBody").getBytes()); else if(emailBodies.get("emailHTMLTableBody") != null) bos.write(emailBodies.get("emailHTMLTableBody").getBytes()); else bos.write(emailBodies.get("emailPlainTextBody").getBytes()); bos.flush(); bos.close(); os.close(); } } catch (Exception e) { Logger.warn(EmailFactory.class, "sendForm: Couldn't save the email backup in " + Config.getStringProperty("EMAIL_BACKUPS")); } // send the mail out; Mailer m = new Mailer(); m.setToEmail(to); m.setFromEmail(from); m.setFromName(fromName); m.setCc(cc); m.setBcc(bcc); m.setSubject(subject); if (html) { if(UtilMethods.isSet(emailBodies.get("emailHTMLBody"))) m.setHTMLBody(emailBodies.get("emailHTMLBody")); else m.setHTMLBody(emailBodies.get("emailHTMLTableBody")); } m.setTextBody(emailBodies.get("emailPlainTextBody")); //Attaching files requested to be attached to the email if(attachFiles != null) { attachFiles = "," + attachFiles.replaceAll("\\s", "") + ","; for(Entry<String, Object> entry : parameters.entrySet()) { if(entry.getValue() instanceof File && attachFiles.indexOf("," + entry.getKey() + ",") > -1) { File f = (File)entry.getValue(); m.addAttachment(f, entry.getKey() + "." + UtilMethods.getFileExtension(f.getName())); } } } if (m.sendMessage()) { // there is an auto reply, send it on if ((UtilMethods.isSet((String)getMapValue("autoReplyTemplate", parameters)) || UtilMethods.isSet((String)getMapValue("autoReplyText", parameters))) && UtilMethods.isSet((String)getMapValue("autoReplySubject", parameters)) && UtilMethods.isSet((String)getMapValue("autoReplyFrom", parameters))) { templatePath = (String) getMapValue("autoReplyTemplate", parameters); if(UtilMethods.isSet(templatePath)) { try { emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user); } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: Couldn't build the auto reply email body text. Sending plain text.", e); } } m = new Mailer(); String autoReplyTo = (String)(getMapValue("autoReplyTo", parameters) == null?getMapValue("from", parameters):getMapValue("autoReplyTo", parameters)); m.setToEmail(UtilMethods.replace(autoReplyTo, "spamx", "")); m.setFromEmail(UtilMethods.replace((String)getMapValue("autoReplyFrom", parameters), "spamx", "")); m.setSubject((String)getMapValue("autoReplySubject", parameters)); String autoReplyText = (String)getMapValue("autoReplyText", parameters); boolean autoReplyHtml = getMapValue("autoReplyHtml", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("autoReplyHtml", parameters)):html; if (autoReplyText != null) { if(autoReplyHtml) { m.setHTMLBody((String)getMapValue("autoReplyText", parameters)); } else { m.setTextBody((String)getMapValue("autoReplyText", parameters)); } } else { if (autoReplyHtml) { if(UtilMethods.isSet(emailBodies.get("emailHTMLBody"))) m.setHTMLBody(emailBodies.get("emailHTMLBody")); else m.setHTMLBody(emailBodies.get("emailHTMLTableBody")); } m.setTextBody(emailBodies.get("emailPlainTextBody")); } m.sendMessage(); } } else { if(formBean != null){ try { HibernateUtil.delete(formBean); } catch (DotHibernateException e) { Logger.error(EmailFactory.class, e.getMessage(), e); } } throw new DotRuntimeException("Unable to send the email"); } return formBean; } public static Map<String, String> buildEmail(String templatePath, Host host, Map<String,Object> parameters, Map<String, String> prettyParametersNamesMap, String filesLinks, String ignoreString, User user) throws WebAssetException, ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, DotDataException, DotSecurityException, PortalException, SystemException { StringBuffer emailHTMLBody = new StringBuffer(); StringBuffer emailHTMLTableBody = new StringBuffer(); StringBuffer emailPlainTextBody = new StringBuffer(); //Case when a html page template is passed as parameter if(UtilMethods.isSet(templatePath)) { Identifier id = APILocator.getIdentifierAPI().find(host,templatePath); String idInode = id.getInode(); String languageId = Long.toString((APILocator.getLanguageAPI().getDefaultLanguage().getId())); try { if(UtilMethods.isSet(parameters.get("languageId"))) { languageId = (String) parameters.get("languageId"); } } catch(ClassCastException e) { Logger.info(EmailFactory.class, "Error parsing languageId"); } String languageStr = "_" + languageId; Template t = null; try { if(InodeUtils.isSet(idInode)) { t = UtilMethods.getVelocityTemplate("live/"+ idInode + languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); } else { t = UtilMethods.getVelocityTemplate(templatePath); } } catch (Exception e) { } if (t != null) { HttpServletRequest request = (HttpServletRequest) parameters.get("request"); HttpServletResponse response = (HttpServletResponse) parameters.get("response"); Context context = null; if(InodeUtils.isSet(idInode) && request != null && response != null) { context = VelocityUtil.getWebContext(request,response); } else { context = VelocityUtil.getBasicContext(); } //Copying the parameters to the context for(Entry<String, Object> entry : parameters.entrySet()) { Object value = getMapValue(entry.getKey(), parameters); if(entry.getKey().equals("ccNumber") && value instanceof String) { value = (String)UtilMethods.obfuscateCreditCard((String)value); } if(entry.getKey().contains("cvv") && value instanceof String) { String valueString = (String)value; if(valueString.length() > 3){ value = (String)UtilMethods.obfuscateString(valueString,2); } else { value = (String)UtilMethods.obfuscateString(valueString,1); } } context.put(entry.getKey(), value); } context.put("utilMethods", new UtilMethods()); context.put("UtilMethods", new UtilMethods()); context.put("host", host); if(user != null) context.put("user", user); StringWriter writer = new StringWriter(); //Rendering the html template with the parameters t.merge(context, writer); String textVar = writer.toString(); emailHTMLBody = new StringBuffer(alterBodyHtmlAbsolutizePaths(replaceTextVar(textVar, parameters, user), host.getHostname())); } } String subject = (String)getMapValue("subject", parameters); subject = (subject == null) ? "Mail from " + host.getHostname(): subject; emailHTMLTableBody.append("<html><style>td{font-family:arial;font-size:10pt;}</style><BODY>"); emailHTMLTableBody.append("<TABLE bgcolor=eeeeee width=95%>"); emailHTMLTableBody.append("<TR><TD colspan=2><strong>Information from " + host.getHostname() + ": " + subject + "</strong></TD></TR>"); emailPlainTextBody.append("Information from " + host.getHostname() + ": \t" + subject + "\n\n"); // Loop over the request Map or the ordered Map Iterator<Entry<String,Object>> it = parameters.entrySet().iterator(); while (it.hasNext()) { Entry<String, Object> e = (Entry<String, Object>) it.next(); String key = e.getKey(); Object mapvalue = getMapValue(key, parameters); if (mapvalue instanceof String) { String value = (String)mapvalue; if(key.equals("ccNumber") && value instanceof String) { value = (String)UtilMethods.obfuscateCreditCard((String)value); } if(key.contains("cvv") && value instanceof String) { String valueString = (String)value; if(valueString.length() > 3){ value = (String)UtilMethods.obfuscateString(valueString,2); } else { value = (String)UtilMethods.obfuscateString(valueString,1); } } if (ignoreString.indexOf(":" + key + ":") < 0 && UtilMethods.isSet(value)) { String prettyKey = prettyParametersNamesMap.get(key); String capKey = prettyKey != null?prettyKey:UtilMethods.capitalize(key); emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap>&nbsp;" + capKey + "&nbsp;</TD>"); emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + value + "</TD></TR>"); emailPlainTextBody.append(capKey + ":\t" + value + "\n"); } } } if (UtilMethods.isSet(filesLinks)) { emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap>&nbsp;Files&nbsp;</TD>"); emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + filesLinks + "</TD></TR>"); emailPlainTextBody.append("Files:\t" + filesLinks + "\n"); } emailHTMLTableBody.append("</TABLE></BODY></HTML>"); Map<String, String> returnMap = new HashMap<String, String>(); if(UtilMethods.isSet(emailHTMLBody.toString())) returnMap.put("emailHTMLBody", emailHTMLBody.toString()); if(UtilMethods.isSet(emailHTMLTableBody.toString())) returnMap.put("emailHTMLTableBody", emailHTMLTableBody.toString()); returnMap.put("emailPlainTextBody", emailPlainTextBody.toString()); return returnMap; } private static WebForm saveFormBean (Map<String, Object> parameters, Host host, String formType, String ignoreString, StringBuffer filesLinks) { //Fields predefined for the form reports String predefinedFields = ":prefix:title:firstName:middleInitial:middleName:lastName:fullName:organization:address:address1:address2:city:state:zip:country:phone:email:"; //Return variable WebForm formBean = new WebForm(); formBean.setFormType(formType); // Copy the common fields set in the form try { for (Entry<String, Object> param : parameters.entrySet()) { BeanUtils.setProperty(formBean, param.getKey(), getMapValue(param.getKey(), parameters)); } } catch (Exception e1) { Logger.error(EmailFactory.class, "sendForm: Error ocurred trying to copy the form bean parameters", e1); } try { HibernateUtil.save(formBean); } catch (DotHibernateException e) { Logger.error(EmailFactory.class, e.getMessage(), e); } String formId = formBean.getWebFormId(); // Loop over the request Map or the ordered Map to set the custom // fields and also saving the submitted files StringBuffer customFields = new StringBuffer(); Set<Entry<String, Object>> paramSet = parameters.entrySet(); for (Entry<String, Object> param : paramSet) { String key = (String) param.getKey(); String value = null; Object paramValue = getMapValue(key, parameters); if (paramValue instanceof File) { File f = (File) param.getValue(); String submittedFileName = f.getName(); String fileName = key + "." + UtilMethods.getFileExtension(submittedFileName); if(getMapValue(fileName.substring(4, key.length()) + "FName", parameters) != null) { fileName = getMapValue(fileName.substring(4, key.length()) + "FName", parameters) + "." + UtilMethods.getFileExtension(submittedFileName); } //Saving the file try { if(f.exists()) { String filesFolder = getMapValue("formFolder", parameters) instanceof String?(String)getMapValue("formFolder", parameters):null; String fileLink = saveFormFile(formId, formType, fileName, f, host, filesFolder); filesLinks.append(filesLinks.toString().equals("")? "http://" + host.getHostname() + fileLink : ",http://" + host.getHostname() + fileLink); } } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: couldn't saved the submitted file into the cms = " + fileName, e); try { HibernateUtil.delete(formBean); } catch (DotHibernateException e1) { Logger.error(EmailFactory.class, e1.getMessage(), e1); } throw new DotRuntimeException("sendForm: couldn't saved the submitted file into the cms = " + fileName, e); } } else if (paramValue instanceof String) value = (String)paramValue; List<String> cFields = new ArrayList<String>(); if (predefinedFields.indexOf(":" + key + ":") < 0 && ignoreString.indexOf(":" + key + ":") < 0 && UtilMethods.isSet(value)) { value = value.replaceAll("\\|", " ").replaceAll("=", " "); if(key.equals("ccNumber")) value = UtilMethods.obfuscateCreditCard(value); String capKey = UtilMethods.capitalize(key); int aux = 2; String capKeyAux = capKey; while (cFields.contains(capKeyAux)) { capKeyAux = capKey + aux; ++aux; } cFields.add(capKeyAux); String cField = capKeyAux + "=" + value; customFields.append(cField + "|"); } } customFields.append("Files=" + filesLinks); //Setting the custom fields and saving them formBean.setCustomFields(customFields.toString()); formBean.setSubmitDate(new Date()); if(UtilMethods.isSet(formType)){ try { HibernateUtil.saveOrUpdate(formBean); } catch (DotHibernateException e) { throw new DotRuntimeException("Webform Save Failed"); } } else{ Logger.debug(EmailFactory.class, "The web form doesn't have the required formType field, the form data will not be saved in the database."); } return formBean; } private static String getFormFileFolderPath (String formType, String formInode) { String path = Config.getStringProperty("SAVED_UPLOAD_FILES_PATH") + "/" + formType.replace(" ", "_") + "/" + String.valueOf(formInode).substring(0, 1) + "/" + formInode; return path; } private static String saveFormFile (String formInode, String formType, String fileName, File fileToSave, Host currentHost, String filesFolder) throws Exception { FileAPI fileAPI=APILocator.getFileAPI(); String path; if(filesFolder != null) path = filesFolder; else path = getFormFileFolderPath(formType, formInode); Folder folder = APILocator.getFolderAPI().createFolders(path, currentHost, APILocator.getUserAPI().getSystemUser(), false); String baseFilename = fileName; int c = 1; while(fileAPI.fileNameExists(folder, fileName)) { fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename); c++; } Host host = APILocator.getHostAPI().find(folder.getHostId(), APILocator.getUserAPI().getSystemUser(), false); while(APILocator.getFileAssetAPI().fileNameExists(host,folder, fileName, "")) { fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename); c++; } Contentlet cont = new Contentlet(); cont.setStructureInode(folder.getDefaultFileType()); cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(fileName)); cont.setFolder(folder.getInode()); cont.setHost(host.getIdentifier()); cont.setBinary(FileAssetAPI.BINARY_FIELD, fileToSave); APILocator.getContentletAPI().checkin(cont, APILocator.getUserAPI().getSystemUser(),false); return path + "/" + fileName; } private static String replaceTextVar(String template, Map<String, Object> parameters, User user) { String finalMessageStr = template; Set<String> keys = parameters.keySet(); for(String key : keys) { if(getMapValue(key, parameters) instanceof String) { String value = (String)getMapValue(key, parameters); value = (value != null ? value : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/"+ key +"(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))" + key + "(\")?( )*/*( )*(>|(&gt;))",value); } } if(UtilMethods.isSet(user)) { Address address = new Address(); try { List<Address> adds = PublicAddressFactory.getAddressesByUserId(user.getUserId()); if (adds != null && adds.size() > 0) { address = (Address) adds.get(0); } } catch(Exception e) { Logger.error(EmailFactory.class, "Send To Friend Failed" + e); } //Variables replacement from user object finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varName(\")?( )*/*( )*(>|(&gt;))", (user.getFirstName()!=null) ? user.getFirstName() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varEmail(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varEmail(\")?( )*/*( )*(>|(&gt;))", (user.getEmailAddress()!=null) ? user.getEmailAddress() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varMiddleName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varMiddleName(\")?( )*/*( )*(>|(&gt;))", (user.getMiddleName()!=null) ? user.getMiddleName() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varLastName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varLastName(\")?( )*/*( )*(>|(&gt;))", (user.getLastName()!=null) ? user.getLastName() : ""); UserProxy userproxy; try { userproxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user,APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error(EmailFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varLastMessage(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varLastMessage(\")?( )*/*( )*(>|(&gt;))", (userproxy.getLastMessage()!=null) ? userproxy.getLastMessage() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varAddress1(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varAddress1(\")?( )*/*( )*(>|(&gt;))", (address.getStreet1()!=null) ? address.getStreet1() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varAddress2(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varAddress2(\")?( )*/*( )*(>|(&gt;))", (address.getStreet2()!=null) ? address.getStreet2() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varPhone(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varPhone(\")?( )*/*( )*(>|(&gt;))", (address.getPhone()!=null) ? address.getPhone() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varState(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varState(\")?( )*/*( )*(>|(&gt;))", (address.getState()!=null) ? address.getState() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varCity(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varCity(\")?( )*/*( )*(>|(&gt;))", (address.getCity()!=null) ? address.getCity() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varCountry(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varCountry(\")?( )*/*( )*(>|(&gt;))", (address.getCountry()!=null) ? address.getCountry() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varZip(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varZip(\")?( )*/*( )*(>|(&gt;))", (address.getZip()!=null) ? address.getZip() : ""); //gets default company to get locale Company comp = PublicCompanyFactory.getDefaultCompany(); try { int varCounter = 1; for (;varCounter < 26;varCounter++) { String var = LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + varCounter); if (var!=null) var = var.replaceAll(" ","_"); String value = ""; try { value = BeanUtils.getSimpleProperty(userproxy, "var" + varCounter); } catch (Exception e) { Logger.error(EmailFactory.class, "An error as ocurred trying to access the variable var" + varCounter + " from the user proxy.", e); } finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/"+var+"(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))" + var + "(\")?( )*/*( )*(>|(&gt;))", (value != null) ? value : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/var" + varCounter + "(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))var" + varCounter + "(\")?( )*/*( )*(>|(&gt;))", (value != null) ? value : ""); } } catch(LanguageException le) { Logger.error(EmailFactory.class, le.getMessage()); } } return finalMessageStr; } public static Object getMapValue(String key, Map<String, Object> map) { try { try { if(((Object[]) map.get(key)).length > 1) { String returnValue = ""; for(Object object : ((Object[]) map.get(key))) { returnValue += object.toString() + ", "; } returnValue = returnValue.substring(0,returnValue.lastIndexOf(",")); return returnValue; } } catch(Exception ex) {} return ((Object[]) map.get(key))[0]; } catch (Exception e) { try { return (Object) map.get(key); } catch (Exception ex) { return null; } } } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5029_1
crossvul-java_data_good_5080_2
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.dataprovider.sql; import java.util.List; import java.util.ArrayList; import org.junit.Before; public class SQLTestSuite extends SQLDataSetTestBase { protected <T extends SQLDataSetTestBase> T setUp(T test) throws Exception { test.testSettings = testSettings; test.conn = conn; return test; } protected List<SQLDataSetTestBase> sqlTestList = new ArrayList<SQLDataSetTestBase>(); @Before public void setUp() throws Exception { super.setUp(); sqlTestList.add(setUp(new SQLDataSetDefTest())); sqlTestList.add(setUp(new SQLDataSetTrimTest())); sqlTestList.add(setUp(new SQLTableDataSetLookupTest())); sqlTestList.add(setUp(new SQLQueryDataSetLookupTest())); sqlTestList.add(setUp(new SQLInjectionAttacksTest())); } public void testAll() throws Exception { for (SQLDataSetTestBase testBase : sqlTestList) { testBase.testAll(); } } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5080_2
crossvul-java_data_bad_5220_1
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.jpa.domain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.PluralAttribute; import org.springframework.data.domain.Sort; import org.springframework.util.Assert; /** * Sort option for queries that wraps JPA meta-model {@link Attribute}s for sorting. * * @author Thomas Darimont * @author Oliver Gierke */ public class JpaSort extends Sort { private static final long serialVersionUID = 1L; /** * Creates a new {@link JpaSort} for the given attributes with the default sort direction. * * @param attributes must not be {@literal null} or empty. */ public JpaSort(Attribute<?, ?>... attributes) { this(DEFAULT_DIRECTION, attributes); } /** * Creates a new {@link JpaSort} instance with the given {@link Path}s. * * @param paths must not be {@literal null} or empty. */ public JpaSort(JpaSort.Path<?, ?>... paths) { this(DEFAULT_DIRECTION, paths); } /** * Creates a new {@link JpaSort} for the given direction and attributes. * * @param direction the sorting direction. * @param attributes must not be {@literal null} or empty. */ public JpaSort(Direction direction, Attribute<?, ?>... attributes) { this(direction, paths(attributes)); } /** * Creates a new {@link JpaSort} for the given direction and {@link Path}s. * * @param direction the sorting direction. * @param paths must not be {@literal null} or empty. */ public JpaSort(Direction direction, Path<?, ?>... paths) { this(direction, Arrays.asList(paths)); } private JpaSort(Direction direction, List<Path<?, ?>> paths) { this(Collections.<Order> emptyList(), direction, paths); } private JpaSort(List<Order> orders, Direction direction, List<Path<?, ?>> paths) { super(combine(orders, direction, paths)); } /** * Returns a new {@link JpaSort} with the given sorting criteria added to the current one. * * @param direction can be {@literal null}. * @param attributes must not be {@literal null}. * @return */ public JpaSort and(Direction direction, Attribute<?, ?>... attributes) { Assert.notNull(attributes, "Attributes must not be null!"); return and(direction, paths(attributes)); } /** * Returns a new {@link JpaSort} with the given sorting criteria added to the current one. * * @param direction can be {@literal null}. * @param paths must not be {@literal null}. * @return */ public JpaSort and(Direction direction, Path<?, ?>... paths) { Assert.notNull(paths, "Paths must not be null!"); List<Order> existing = new ArrayList<Order>(); for (Order order : this) { existing.add(order); } return new JpaSort(existing, direction, Arrays.asList(paths)); } /** * Turns the given {@link Attribute}s into {@link Path}s. * * @param attributes must not be {@literal null} or empty. * @return */ private static Path<?, ?>[] paths(Attribute<?, ?>[] attributes) { Assert.notNull(attributes, "Attributes must not be null!"); Assert.isTrue(attributes.length > 0, "Attributes must not be empty"); Path<?, ?>[] paths = new Path[attributes.length]; for (int i = 0; i < attributes.length; i++) { paths[i] = path(attributes[i]); } return paths; } private static List<Order> combine(List<Order> orders, Direction direction, List<Path<?, ?>> paths) { List<Order> result = new ArrayList<Sort.Order>(orders); for (Path<?, ?> path : paths) { result.add(new Order(direction, path.toString())); } return result; } /** * Creates a new {@link Path} for the given {@link Attribute}. * * @param attribute must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") public static <A extends Attribute<T, S>, T, S> Path<T, S> path(A attribute) { Assert.notNull(attribute, "Attribute must not be null!"); return new Path<T, S>(Arrays.asList(attribute)); } /** * Creates a new {@link Path} for the given {@link PluralAttribute}. * * @param attribute must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") public static <P extends PluralAttribute<T, ?, S>, T, S> Path<T, S> path(P attribute) { Assert.notNull(attribute, "Attribute must not be null!"); return new Path<T, S>(Arrays.asList(attribute)); } /** * Value object to abstract a collection of {@link Attribute}s. * * @author Oliver Gierke */ public static class Path<T, S> { private final Collection<Attribute<?, ?>> attributes; private Path(List<? extends Attribute<?, ?>> attributes) { this.attributes = Collections.unmodifiableList(attributes); } /** * Collects the given {@link Attribute} and returning a new {@link Path} pointing to the attribute type. * * @param attribute must not be {@literal null}. * @return */ public <A extends Attribute<S, U>, U> Path<S, U> dot(A attribute) { return new Path<S, U>(add(attribute)); } /** * Collects the given {@link PluralAttribute} and returning a new {@link Path} pointing to the attribute type. * * @param attribute must not be {@literal null}. * @return */ public <P extends PluralAttribute<S, ?, U>, U> Path<S, U> dot(P attribute) { return new Path<S, U>(add(attribute)); } private List<Attribute<?, ?>> add(Attribute<?, ?> attribute) { Assert.notNull(attribute, "Attribute must not be null!"); List<Attribute<?, ?>> newAttributes = new ArrayList<Attribute<?, ?>>(attributes.size() + 1); newAttributes.addAll(attributes); newAttributes.add(attribute); return newAttributes; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Attribute<?, ?> attribute : attributes) { builder.append(attribute.getName()).append("."); } return builder.length() == 0 ? "" : builder.substring(0, builder.lastIndexOf(".")); } } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5220_1
crossvul-java_data_good_5029_2
package com.dotmarketing.portlets.workflows.model; import java.net.URLEncoder; import java.util.List; import java.util.Map; import com.dotmarketing.business.APILocator; import com.dotmarketing.common.util.SQLUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.util.UtilMethods; import com.liferay.portal.model.User; public class WorkflowSearcher { String schemeId; String assignedTo; String createdBy; String stepId; boolean open; boolean closed; boolean show4all; String keywords; String orderBy; int count = 20; int page = 0; User user; int totalCount; int daysOld=-1; public int getDaysOld() { return daysOld; } public boolean getShow4All() { return show4all; } public void setShow4All(boolean value) { show4all=value; } public int getTotalCount() { return totalCount; } public String getAssignedTo() { return assignedTo; } public void setAssignedTo(String assignedTo) { this.assignedTo = assignedTo; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } private String getStringValue(String x, Map<String, Object> map) { Object obj = map.get(x); if (obj == null) return null; String ret = null; if (obj instanceof String[]) { ret = ((String[]) obj)[0]; } else { ret = obj.toString(); } return (UtilMethods.isSet(ret)) ? ret : null; } private boolean getBooleanValue(String x, Map<String, Object> map) { Object obj = map.get(x); String y = null; try { if (obj instanceof String[]) { y = ((String[]) obj)[0]; } else { y = obj.toString(); } return new Boolean(y); } catch (Exception e) { } return false; } public WorkflowSearcher() { } public WorkflowSearcher(Map<String, Object> map, User user) { schemeId = getStringValue("schemeId", map); assignedTo = getStringValue("assignedTo", map); createdBy = getStringValue("createdBy", map); stepId = getStringValue("stepId", map); keywords = getStringValue("keywords", map); orderBy = getStringValue("orderBy", map); orderBy= SQLUtil.sanitizeSortBy(orderBy); show4all = getBooleanValue("show4all", map); open = getBooleanValue("open", map); closed = getBooleanValue("closed", map); String daysOldstr = getStringValue("daysold", map); if(UtilMethods.isSet(daysOldstr) && daysOldstr.matches("^\\d+$")) daysOld = Integer.parseInt(daysOldstr); this.user = user; try { page = Integer.parseInt((String) getStringValue("page", map)); } catch (Exception e) { page = 0; } if (page < 0) page = 0; try { count = Integer.parseInt((String) getStringValue("count", map)); } catch (Exception e) { count = 20; } if (count < 0) count = 20; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getOrderBy() { return SQLUtil.sanitizeSortBy(orderBy); } public List<WorkflowTask> findTasks() throws DotDataException { totalCount = APILocator.getWorkflowAPI().countTasks(this); return APILocator.getWorkflowAPI().searchTasks(this); } public List<WorkflowTask> findAllTasks(WorkflowSearcher searcher) throws DotDataException { List<WorkflowTask> list = APILocator.getWorkflowAPI().searchAllTasks(searcher); totalCount = (APILocator.getWorkflowAPI().searchAllTasks(null)).size(); return list; } public void setOrderBy(String orderBy) { orderBy = SQLUtil.sanitizeSortBy(orderBy); this.orderBy = orderBy; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getSchemeId() { return schemeId; } public void setSchemeId(String schemeId) { this.schemeId = schemeId; } public String getStepId() { return stepId; } public void setStepId(String actionId) { this.stepId = actionId; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public boolean isClosed() { return closed; } public void setClosed(boolean closed) { this.closed = closed; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getQueryString() { return "&schemeId=" + UtilMethods.webifyString(schemeId) + "&assignedTo=" + UtilMethods.webifyString(assignedTo) + "&createdBy=" + UtilMethods.webifyString(createdBy) + "&stepId=" + UtilMethods.webifyString(stepId) + "&open=" + open + "&closed=" + closed + "&keywords=" + URLEncoder.encode(UtilMethods.webifyString(keywords)) + "&orderBy=" + orderBy + "&count=" + count + ((show4all) ? "&show4all=true" : "") + "&page=" + page; } public String getQueryStringBis() { return "&count=" + count + "&page=" + page; } public boolean hasBack() { return page > 0; } public boolean hasNext() { return (count * (page + 1)) < totalCount; } public int getTotalPages() { return ((totalCount - 1) / count) + 1; } public int getStartPage() { int startPages = 0; int pages = getTotalPages(); if (pages > 10 && page > pages - 10) { startPages = pages - 10; } return startPages; } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5029_2
crossvul-java_data_bad_5029_2
package com.dotmarketing.portlets.workflows.model; import java.net.URLEncoder; import java.util.List; import java.util.Map; import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.util.UtilMethods; import com.liferay.portal.model.User; public class WorkflowSearcher { String schemeId; String assignedTo; String createdBy; String stepId; boolean open; boolean closed; boolean show4all; String keywords; String orderBy; int count = 20; int page = 0; User user; int totalCount; int daysOld=-1; public int getDaysOld() { return daysOld; } public boolean getShow4All() { return show4all; } public void setShow4All(boolean value) { show4all=value; } public int getTotalCount() { return totalCount; } public String getAssignedTo() { return assignedTo; } public void setAssignedTo(String assignedTo) { this.assignedTo = assignedTo; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } private String getStringValue(String x, Map<String, Object> map) { Object obj = map.get(x); if (obj == null) return null; String ret = null; if (obj instanceof String[]) { ret = ((String[]) obj)[0]; } else { ret = obj.toString(); } return (UtilMethods.isSet(ret)) ? ret : null; } private boolean getBooleanValue(String x, Map<String, Object> map) { Object obj = map.get(x); String y = null; try { if (obj instanceof String[]) { y = ((String[]) obj)[0]; } else { y = obj.toString(); } return new Boolean(y); } catch (Exception e) { } return false; } public WorkflowSearcher() { } public WorkflowSearcher(Map<String, Object> map, User user) { schemeId = getStringValue("schemeId", map); assignedTo = getStringValue("assignedTo", map); createdBy = getStringValue("createdBy", map); stepId = getStringValue("stepId", map); keywords = getStringValue("keywords", map); orderBy = getStringValue("orderBy", map); show4all = getBooleanValue("show4all", map); open = getBooleanValue("open", map); closed = getBooleanValue("closed", map); String daysOldstr = getStringValue("daysold", map); if(UtilMethods.isSet(daysOldstr) && daysOldstr.matches("^\\d+$")) daysOld = Integer.parseInt(daysOldstr); this.user = user; try { page = Integer.parseInt((String) getStringValue("page", map)); } catch (Exception e) { page = 0; } if (page < 0) page = 0; try { count = Integer.parseInt((String) getStringValue("count", map)); } catch (Exception e) { count = 20; } if (count < 0) count = 20; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getOrderBy() { return orderBy; } public List<WorkflowTask> findTasks() throws DotDataException { totalCount = APILocator.getWorkflowAPI().countTasks(this); return APILocator.getWorkflowAPI().searchTasks(this); } public List<WorkflowTask> findAllTasks(WorkflowSearcher searcher) throws DotDataException { List<WorkflowTask> list = APILocator.getWorkflowAPI().searchAllTasks(searcher); totalCount = (APILocator.getWorkflowAPI().searchAllTasks(null)).size(); return list; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getSchemeId() { return schemeId; } public void setSchemeId(String schemeId) { this.schemeId = schemeId; } public String getStepId() { return stepId; } public void setStepId(String actionId) { this.stepId = actionId; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public boolean isClosed() { return closed; } public void setClosed(boolean closed) { this.closed = closed; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getQueryString() { return "&schemeId=" + UtilMethods.webifyString(schemeId) + "&assignedTo=" + UtilMethods.webifyString(assignedTo) + "&createdBy=" + UtilMethods.webifyString(createdBy) + "&stepId=" + UtilMethods.webifyString(stepId) + "&open=" + open + "&closed=" + closed + "&keywords=" + URLEncoder.encode(UtilMethods.webifyString(keywords)) + "&orderBy=" + orderBy + "&count=" + count + ((show4all) ? "&show4all=true" : "") + "&page=" + page; } public String getQueryStringBis() { return "&count=" + count + "&page=" + page; } public boolean hasBack() { return page > 0; } public boolean hasNext() { return (count * (page + 1)) < totalCount; } public int getTotalPages() { return ((totalCount - 1) / count) + 1; } public int getStartPage() { int startPages = 0; int pages = getTotalPages(); if (pages > 10 && page > pages - 10) { startPages = pages - 10; } return startPages; } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5029_2
crossvul-java_data_bad_5080_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5080_1
crossvul-java_data_bad_5080_2
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.dataprovider.sql; import java.util.List; import java.util.ArrayList; import org.junit.Before; public class SQLTestSuite extends SQLDataSetTestBase { protected <T extends SQLDataSetTestBase> T setUp(T test) throws Exception { test.testSettings = testSettings; test.conn = conn; return test; } protected List<SQLDataSetTestBase> sqlTestList = new ArrayList<SQLDataSetTestBase>(); @Before public void setUp() throws Exception { super.setUp(); sqlTestList.add(setUp(new SQLDataSetDefTest())); sqlTestList.add(setUp(new SQLDataSetTrimTest())); sqlTestList.add(setUp(new SQLTableDataSetLookupTest())); sqlTestList.add(setUp(new SQLQueryDataSetLookupTest())); } public void testAll() throws Exception { for (SQLDataSetTestBase testBase : sqlTestList) { testBase.testAll(); } } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5080_2
crossvul-java_data_good_5029_0
package com.dotmarketing.cms.webforms.action; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dotcms.enterprise.PasswordFactoryProxy; import com.dotcms.repackage.nl.captcha.Captcha; import com.dotcms.repackage.org.apache.struts.Globals; import com.dotcms.repackage.org.apache.struts.action.ActionErrors; import com.dotcms.repackage.org.apache.struts.action.ActionForm; import com.dotcms.repackage.org.apache.struts.action.ActionForward; import com.dotcms.repackage.org.apache.struts.action.ActionMapping; import com.dotcms.repackage.org.apache.struts.action.ActionMessage; import com.dotcms.repackage.org.apache.struts.actions.DispatchAction; import com.dotcms.util.SecurityUtils; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.UserProxy; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.Role; import com.dotmarketing.business.web.HostWebAPI; import com.dotmarketing.business.web.WebAPILocator; import com.dotmarketing.cms.factories.PublicAddressFactory; import com.dotmarketing.cms.factories.PublicCompanyFactory; import com.dotmarketing.cms.factories.PublicEncryptionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.factories.ClickstreamFactory; import com.dotmarketing.factories.EmailFactory; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.portlets.categories.model.Category; import com.dotmarketing.portlets.user.factories.UserCommentsFactory; import com.dotmarketing.portlets.user.model.UserComment; import com.dotmarketing.portlets.webforms.model.WebForm; import com.dotmarketing.util.Config; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.model.Address; import com.liferay.portal.model.Company; import com.liferay.portal.model.User; import com.liferay.util.servlet.UploadServletRequest; /** * * @author David * @version $Revision: 1.5 $ $Date: 2007/07/18 16:48:42 $ */ public final class SubmitWebFormAction extends DispatchAction { HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI(); @SuppressWarnings("unchecked") public ActionForward unspecified(ActionMapping rMapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); //Email parameters HttpSession session = request.getSession(); Host currentHost = hostWebAPI.getCurrentHost(request); User currentUser = (User) session.getAttribute(WebKeys.CMS_USER); String method = request.getMethod(); String errorURL = request.getParameter("errorURL"); errorURL = (!UtilMethods.isSet(errorURL) ? request.getHeader("referer") : errorURL); if(errorURL.indexOf("?") > -1) { errorURL = errorURL.substring(0,errorURL.lastIndexOf("?")); } String x = request.getRequestURI(); if(request.getParameterMap().size() <2){ return null; } //Checking for captcha boolean useCaptcha = Config.getBooleanProperty("FORCE_CAPTCHA",true); if(!useCaptcha){ useCaptcha = new Boolean(request.getParameter("useCaptcha")).booleanValue(); } String captcha = request.getParameter("captcha"); if (useCaptcha) { Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME); String captchaSession=captchaObj!=null ? captchaObj.getAnswer() : null; if(captcha ==null && Config.getBooleanProperty("FORCE_CAPTCHA",true)){ response.getWriter().write("Captcha is required to submit this form ( FORCE_CAPTCHA=true ).<br>To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false"); return null; } if(!UtilMethods.isSet(captcha) || !UtilMethods.isSet(captchaSession) || !captcha.equals(captchaSession)) { errors.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", "Validation Image")); request.setAttribute(Globals.ERROR_KEY, errors); session.setAttribute(Globals.ERROR_KEY, errors); String queryString = request.getQueryString(); String invalidCaptchaURL = request.getParameter("invalidCaptchaReturnUrl"); if(!UtilMethods.isSet(invalidCaptchaURL)) { invalidCaptchaURL = errorURL; } invalidCaptchaURL = invalidCaptchaURL.replaceAll("\\s", " "); ActionForward af = new ActionForward(); af.setRedirect(true); if (UtilMethods.isSet(queryString)) { af.setPath(invalidCaptchaURL + "?" + queryString + "&error=Validation-Image"); } else { af.setPath(invalidCaptchaURL + "?error=Validation-Image"); } return af; } } Map<String, Object> parameters = null; if (request instanceof UploadServletRequest) { UploadServletRequest uploadReq = (UploadServletRequest) request; parameters = new HashMap<String, Object> (uploadReq.getParameterMap()); for (Entry<String, Object> entry : parameters.entrySet()) { if(entry.getKey().toLowerCase().indexOf("file") > -1 && !entry.getKey().equals("attachFiles")) { parameters.put(entry.getKey(), uploadReq.getFile(entry.getKey())); } } } else { parameters = new HashMap<String, Object> (request.getParameterMap()); } Set<String> toValidate = new java.util.HashSet<String>(parameters.keySet()); //Enhancing the ignored parameters not to be send in the email String ignoredParameters = (String) EmailFactory.getMapValue("ignore", parameters); if(ignoredParameters == null) { ignoredParameters = ""; } ignoredParameters += ":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:"; parameters.put("ignore", ignoredParameters); // getting categories from inodes // getting parent category name and child categories name // and replacing the "categories" parameter String categories = ""; String[] categoriesArray = request.getParameterValues("categories"); if (categoriesArray != null) { HashMap hashCategories = new HashMap<String, String>(); for (int i = 0; i < categoriesArray.length; i++) { Category node = (Category) InodeFactory.getInode(categoriesArray[i], Category.class); Category parent = (Category) InodeFactory.getParentOfClass(node, Category.class); String parentCategoryName = parent.getCategoryName(); if (hashCategories.containsKey(parentCategoryName)) { String childCategoryName = (String) hashCategories.get(parentCategoryName); if (UtilMethods.isSet(childCategoryName)) { childCategoryName += ", "; } childCategoryName += node.getCategoryName(); hashCategories.put(parentCategoryName, childCategoryName); } else { hashCategories.put(parentCategoryName, node.getCategoryName()); } } Set<String> keySet = hashCategories.keySet(); for (String stringKey: keySet) { if (UtilMethods.isSet(categories)) { categories += "; "; } categories += stringKey + " : " + (String) hashCategories.get(stringKey); parameters.put(stringKey, (String) hashCategories.get(stringKey)); } parameters.remove("categories"); } WebForm webForm = new WebForm(); try { /*validation parameter should ignore the returnUrl and erroURL field in the spam check*/ String[] removeParams = ignoredParameters.split(":"); for(String param : removeParams){ toValidate.remove(param); } parameters.put("request", request); parameters.put("response", response); //Sending the email webForm = EmailFactory.sendParameterizedEmail(parameters, toValidate, currentHost, currentUser); webForm.setCategories(categories); if(UtilMethods.isSet(request.getParameter("createAccount")) && request.getParameter("createAccount").equals("true")) { //if we create account set to true we create a user account and add user comments. createAccount(webForm, request); try{ String userInode = webForm.getUserInode(); String customFields = webForm.getCustomFields(); customFields += " User Inode = " + String.valueOf(userInode) + " | "; webForm.setCustomFields(customFields); } catch(Exception e){ } } if(UtilMethods.isSet(webForm.getFormType())){ HibernateUtil.saveOrUpdate(webForm); } if (request.getParameter("return") != null) { ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("return"))); af.setRedirect(true); return af; } else if (request.getParameter("returnUrl") != null) { ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("returnUrl"))); af.setRedirect(true); return af; } else { return rMapping.findForward("thankYouPage"); } } catch (DotRuntimeException e) { errors.add(Globals.ERROR_KEY, new ActionMessage("error.processing.your.email")); request.getSession().setAttribute(Globals.ERROR_KEY, errors); String queryString = request.getQueryString(); if (queryString == null) { java.util.Enumeration<String> parameterNames = request.getParameterNames(); queryString = ""; String parameterName; for (; parameterNames.hasMoreElements();) { parameterName = parameterNames.nextElement(); if (0 < queryString.length()) { queryString = queryString + "&" + parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName)); } else { queryString = parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName)); } } } ActionForward af; if (UtilMethods.isSet(queryString)) { af = new ActionForward(SecurityUtils.stripReferer(request, errorURL + "?" + queryString)); } else { af = new ActionForward(SecurityUtils.stripReferer(request, errorURL)); } af.setRedirect(true); return af; } } private void createAccount(WebForm form, HttpServletRequest request) throws Exception { User user = APILocator.getUserAPI().loadByUserByEmail(form.getEmail(), APILocator.getUserAPI().getSystemUser(), false); User defaultUser = APILocator.getUserAPI().getDefaultUser(); Date today = new Date(); if (user.isNew() || (!user.isNew() && user.getLastLoginDate() == null)) { // ### CREATE USER ### Company company = PublicCompanyFactory.getDefaultCompany(); user.setEmailAddress(form.getEmail().trim().toLowerCase()); user.setFirstName(form.getFirstName() == null ? "" : form.getFirstName()); user.setMiddleName(form.getMiddleName() == null ? "" : form.getMiddleName()); user.setLastName(form.getLastName() == null ? "" : form.getLastName()); user.setNickName(""); user.setCompanyId(company.getCompanyId()); user.setGreeting("Welcome, " + user.getFullName() + "!"); // Set defaults values if (user.isNew()) { //if it's a new user we set random password String pass = PublicEncryptionFactory.getRandomPassword(); // Use new password hash method user.setPassword(PasswordFactoryProxy.generateHash(pass)); user.setLanguageId(defaultUser.getLanguageId()); user.setTimeZoneId(defaultUser.getTimeZoneId()); user.setSkinId(defaultUser.getSkinId()); user.setDottedSkins(defaultUser.isDottedSkins()); user.setRoundedSkins(defaultUser.isRoundedSkins()); user.setResolution(defaultUser.getResolution()); user.setRefreshRate(defaultUser.getRefreshRate()); user.setLayoutIds(""); user.setActive(true); user.setCreateDate(today); } APILocator.getUserAPI().save(user,APILocator.getUserAPI().getSystemUser(),false); // ### END CREATE USER ### // ### CREATE USER_PROXY ### UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user.getUserId(),APILocator.getUserAPI().getSystemUser(), false); userProxy.setPrefix(""); userProxy.setTitle(form.getTitle()); userProxy.setOrganization(form.getOrganization()); userProxy.setUserId(user.getUserId()); com.dotmarketing.business.APILocator.getUserProxyAPI().saveUserProxy(userProxy,APILocator.getUserAPI().getSystemUser(), false); // ### END CRETE USER_PROXY ### // saving user inode on web form form.setUserInode(userProxy.getInode()); if(UtilMethods.isSet(form.getFormType())){ HibernateUtil.saveOrUpdate(form); } ///// WE CAN DO THIS! BUT WE NEED TO ADD CATEGORIES TO WEBFORM AND ALSO CHANGE THE PROCESSES THAT //// CREATE THE EXCEL DOWNLOAD FROM WEB FORMS. I DIDN'T ADD IT SO I COMMENTED THIS CODE FOR NOW //get the old categories, wipe them out /* List<Category> categories = InodeFactory.getParentsOfClass(userProxy, Category.class); for (int i = 0; i < categories.size(); i++) { categories.get(i).deleteChild(userProxy); } */ // Save the new categories /*String[] arr = form.getCategories(); if (arr != null) { for (int i = 0; i < arr.length; i++) { Category node = (Category) InodeFactory.getInode(arr[i], Category.class); node.addChild(userProxy); } }*/ // ### CREATE ADDRESS ### try { List<Address> addresses = PublicAddressFactory.getAddressesByUserId(user.getUserId()); Address address = (addresses.size() > 0 ? addresses.get(0) : PublicAddressFactory.getInstance()); address.setStreet1(form.getAddress1() == null ? "" : form.getAddress1()); address.setStreet2(form.getAddress2() == null ? "" : form.getAddress2()); address.setCity(form.getCity() == null ? "" : form.getCity()); address.setState(form.getState() == null ? "" : form.getState()); address.setZip(form.getZip() == null ? "" : form.getZip()); String phone = form.getPhone(); address.setPhone(phone == null ? "" : phone); address.setUserId(user.getUserId()); address.setCompanyId(company.getCompanyId()); PublicAddressFactory.save(address); } catch (Exception ex) { Logger.error(this,ex.getMessage(),ex); } Role defaultRole = com.dotmarketing.business.APILocator.getRoleAPI().loadRoleByKey(Config.getStringProperty("CMS_VIEWER_ROLE")); String roleId = defaultRole.getId(); if (InodeUtils.isSet(roleId)) { com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user); } } // ### END CREATE ADDRESS ### // ### BUILD THE USER COMMENT ### addUserComments(user.getUserId(),form,request); // ### END BUILD THE USER COMMENT ### /* associate user with their clickstream request */ if(Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)){ ClickstreamFactory.setClickStreamUser(user.getUserId(), request); } } private void addUserComments(String userid, WebForm webForm, HttpServletRequest request) throws Exception { Date now = new Date(); String webFormType = webForm.getFormType(); String webFormId = webForm.getWebFormId(); UserComment userComments = new UserComment(); userComments.setUserId(userid); userComments.setCommentUserId(userid); userComments.setDate(now); if (request.getParameter("comments")!=null) { userComments.setComment(request.getParameter("comments")); } else if(UtilMethods.isSet(webForm.getFormType())) { userComments.setSubject("User submitted: " + webFormType); userComments.setComment("Web Form: " + webFormType + " - ID: " + webFormId); } else{ userComments.setSubject("User submitted Form: Open Entry "); StringBuffer buffy = new StringBuffer(); Enumeration x = request.getParameterNames(); while(x.hasMoreElements()){ String key = (String) x.nextElement(); buffy.append(key); buffy.append(":\t"); buffy.append(request.getParameter(key)); buffy.append("\n"); if(buffy.length() > 65000){ break; } } userComments.setComment(buffy.toString()); } userComments.setTypeComment(UserComment.TYPE_INCOMING); userComments.setMethod(UserComment.METHOD_WEB); userComments.setCommunicationId(null); UserCommentsFactory.saveUserComment(userComments); } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5029_0
crossvul-java_data_bad_5029_1
package com.dotmarketing.factories; //import com.dotmarketing.threads.DeliverNewsletterThread; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils; import org.apache.velocity.Template; import org.apache.velocity.context.Context; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.UserProxy; import com.dotmarketing.business.APILocator; import com.dotmarketing.cms.factories.PublicAddressFactory; import com.dotmarketing.cms.factories.PublicCompanyFactory; import com.dotmarketing.cms.factories.PublicEncryptionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.exception.WebAssetException; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.fileassets.business.FileAssetAPI; import com.dotmarketing.portlets.files.business.FileAPI; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory; import com.dotmarketing.portlets.mailinglists.model.MailingList; import com.dotmarketing.portlets.webforms.model.WebForm; import com.dotmarketing.util.Config; import com.dotmarketing.util.FormSpamFilter; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.Mailer; import com.dotmarketing.util.Parameter; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.VelocityUtil; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.liferay.portal.language.LanguageException; import com.liferay.portal.language.LanguageUtil; import com.liferay.portal.model.Address; import com.liferay.portal.model.Company; import com.liferay.portal.model.User; import com.liferay.util.FileUtil; /** * DOCUMENT ME! * * @author $author$ * @version $Revision: 1.10 $ */ public class EmailFactory { private static Long emailTime = new Long(System.currentTimeMillis()); /** * Rewrites urls to point back to the redirection servlet to track links * and then calls the alterBodyHtmlAbsolutizePaths method */ public static StringBuffer alterBodyHTML(StringBuffer HTML, String serverName) { return new StringBuffer(alterBodyHTML(HTML.toString(), serverName)); } public static String alterBodyHTML(String HTML, String serverName) { //This is the new Regular Expression for white spaces ([ .\r\n&&[^>]]*) // Replacing links "a href" like tags axcluding the mail to links HTML = HTML.replaceAll("(?i)(?s)<a[^>]+href=\"([^/(http://)(https://)(#)(mailto:\")])(.*)\"[^>]*>", "<a href=\"http://$1$2\">"); HTML = HTML.replaceAll( //"(?i)(?s)<a[^>]+href=\"([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>", "(?i)(?s)<a href=\"([^#])([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>", "<a href=\"http://" + serverName //+ "/redirect?r=<rId>&redir=$1\">$2</a>") + "/redirect?r=<rId>&redir=$1$2\">$3</a>") .replaceAll("<a href=\"http://" + serverName + "/redirect\\?r=<rId>&redir=(mailto:[^\"]+)\">", "<a href=\"$1\">"); HTML = alterBodyHtmlAbsolutizePaths(HTML, serverName); return HTML; } /** * Change all the relative paths in the email body to absolute paths */ public static StringBuffer alterBodyHtmlAbsolutizePaths(StringBuffer HTML, String serverName) { return new StringBuffer(alterBodyHtmlAbsolutizePaths(HTML.toString(), serverName)); } public static String alterBodyHtmlAbsolutizePaths(String HTML, String serverName) { String message = HTML; //Replacing links "TD background" like tags message = message .replaceAll( "<\\s*td([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<td$1background=\"http://" + serverName + "$2\"$3>"); // Replacing links "TR background" like tags message = message .replaceAll( "<\\s*tr([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<tr$1background=\"http://" + serverName + "$2\"$3>"); // Replacing links "IMG SRC" like tags message = message.replaceAll( "<\\s*img([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<img$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "A HREF" like tags message = message .replaceAll( "<\\s*link([^>]*)href\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<link$1href=\"http://" + serverName + "$2\"$3>"); // Replacing links "SCRIPT" like tags message = message .replaceAll( "<\\s*script([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<script$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "APPLET" with codebase like tags message = message .replaceAll( "<\\s*applet([^>]*)codebase\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<applet$1codebase=\"http://" + serverName + "$2\"$3>"); // Replacing links "APPLET" without codebase like tags message = message .replaceAll( "<\\s*applet(([^>][^(codebase)])*)code\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?(([^>][^(codebase)])*)>", "<applet$1code=\"http://" + serverName + "$4\"$5>"); // Replacing links "IFRAME" src replacement message = message .replaceAll( "<\\s*iframe([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<iframe$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "IFRAME" longdesc replacement message = message .replaceAll( "<\\s*iframe([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<iframe$1longdesc=\"http://" + serverName + "$2\"$3>"); // Replacing links "FRAME" src replacement message = message .replaceAll( "<\\s*frame([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<frame$1src=\"http://" + serverName + "$2\"$3>"); // Replacing links "FRAME" longdesc replacement message = message .replaceAll( "<\\s*frame([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>", "<frame$1longdesc=\"http://" + serverName + "$2\"$3>"); // Replacing some style URLs message = message .replaceAll( "<([^>]*)style\\s*=\\s*[\"\']?([^\'\">]*)url\\s*\\(\\s*([^>]*)\\s*\\)([^\'\">]*)[\"\']?([^>]*)>", "<$1style=\"$2url(http://" + serverName + "$3)$4\"$5>"); // Fixing absolute paths message = message.replaceAll("http://" + serverName + "\\s*http://", "http://"); return message; } /** * Sends the forgot password email with the new random generated password * @throws DotSecurityException * @throws DotDataException */ public static boolean sendForgotPassword(User user, String newPassword, String hostId) throws DotDataException, DotSecurityException { HostAPI hostAPI = APILocator.getHostAPI(); // build a decent default context Context context = VelocityUtil.getBasicContext(); context.put("user", user); context.put("UtilMethods", new UtilMethods()); context.put("language", Long.toString(APILocator.getLanguageAPI().getDefaultLanguage().getId())); context.put("password", newPassword); Host host = hostAPI.find(hostId, user, true); context.put("host", host); StringWriter writer = new StringWriter(); String idInode = APILocator.getIdentifierAPI().find(host, Config .getStringProperty("PATH_FORGOT_PASSWORD_EMAIL")).getInode(); String languageStr = "_" + APILocator.getLanguageAPI().getDefaultLanguage().getId(); try { String message = ""; try { Template t = UtilMethods.getVelocityTemplate("live/"+ idInode+ languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); t.merge(context, writer); Logger .debug(EmailFactory.class, "writer:" + writer.getBuffer()); message = writer.toString().trim(); } catch (ResourceNotFoundException ex) { message = "<center><b>And error has ocurred loading de message's page<b></center>"; } Mailer m = new Mailer(); m.setToEmail(user.getEmailAddress()); m.setSubject("Your " + host.getHostname() + " Password"); m.setHTMLBody(message); m.setFromEmail(Config.getStringProperty("EMAIL_SYSTEM_ADDRESS")); return m.sendMessage(); } catch (Exception e) { Logger.warn(EmailFactory.class, e.toString(), e); return false; } } public static boolean isSubscribed(MailingList list, User s){ UserProxy up; try { up = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(s,APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error(EmailFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return MailingListFactory.isSubscribed(list, up); } /** * * Send emails based on the parameters given to the method, basically is used * to send emails based on parameters received html forms but it can be used * to send emails using parameters that come form any source * * Some parameters are required and need to be passed in order the method to work * correctly, here it is the description of the predefined parameters and when they are * required or not: * * formType/formName: The name of the form used to generate the reports and to save the files submitted * as parameters, so if no formType or formName is supplied then no report * or files will be saved. * to: Email address where the email will be sent * from: Email address will be used as the from address * subject: Subject of the email * cc: Carbon copy of the email * bcc: Hidden carbon copy of the email * html: Set it to false|0|f if you don't want to send an html kind of email * dispatch: Not used reserved for struts processing * order: Order how you want to present the parameters, the valid syntax of this * parameter is like: param1,param2,... * prettyOrder: This property goes together with the order property to specify * prettiest names to the parameters, these prettiest names are used * when building the simple html table e-mail * ignore: Parameters you want to exclude from the email sent, the valid syntax of this * parameter is like ;param1;param2;..., this is only used when building the * simple html table email body and not when building the email from a given template * emailTemplate: The path to the email template to be used to generate the email * it can be a path in the dotCMS tree or a real path in the server file system * under /liferay folder, dotCMS paths take precedence over filesystem paths * attachFiles: A comma separated list of the file kind of fields you want the method include as * attachments to the email to send * If the following parameters are included an auto reply message will be send * to the from email * autoReplyFrom: Address to be used as the from * autoReplySubject: Subject of the message * autoReplyText: Message to send * autoReplyTemplate: A path to an html template that can be used to generate this message * it can be a path in the dotCMS tree or a real path in the server file system * under /liferay folder * * @param parameters A map of the submitted fields, any kind of parameter can * be used and will be passed to the email template to render the email body text used when * sending the email but only string or file kind parameters will be used to generate the database * reports and generate plain table html table like body text when no html template is passed * in the parameters * * @param spamValidation List of fields that wants to be checked for possible spam * @param otherIgnoredParams A list of other fields (more than the default ones) that you want to * be excluded from the list of fields to be sent in the email * @param host Current dotCMS host used to submit the form * @param user User how submits the form (can be null then the user parameters won't be excluded * on the template substitution) * @return The saved webform if a formType/formName parameter is specified if not returns null. * @throws DotRuntimeException when spam is detected or any other mayor error occurs * CreditCardDeniedException when the credit card gets denied */ public static WebForm sendParameterizedEmail(Map<String,Object> parameters, Set<String> spamValidation, Host host, User user) throws DotRuntimeException { // check for possible spam if(spamValidation != null) if (FormSpamFilter.isSpamRequest(parameters, spamValidation)) { throw new DotRuntimeException("Spam detected"); } //Variables initialization //Default parameters to be ignored when sending the email String ignoreString = ":formType:formName:to:from:subject:cc:bcc:html:dispatch:order:" + "prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:" + "ignore:emailTemplate:autoReplyTemplate:autoReplyHtml:chargeCreditCard:attachFiles:"; if(UtilMethods.isSet(getMapValue("ignore", parameters))) { ignoreString += getMapValue("ignore", parameters).toString().replace(",", ":") + ":"; } // Sort the forms' fields by the given order parameter String order = (String)getMapValue("order", parameters); Map<String, Object> orderedMap = new LinkedHashMap<String, Object>(); // Parameter prettyOrder is used to map // the pretty names of the variables used in the order field // E.G: order = firstName, lastName // prettyOrder = First Name, Last Name String prettyOrder = (String)getMapValue("prettyOrder", parameters); Map<String, String> prettyVariableNamesMap = new LinkedHashMap<String, String>(); // Parameter attachFiles is used to specify the file kind of fields you want to attach // to the mail is sent by this method // E.G: attachFiles = file1, file2, ... String attachFiles = (String)getMapValue("attachFiles", parameters); //Building the parameters maps from the order and pretty order parameters if (order != null) { String[] orderArr = order.split("[;,]"); String[] prettyOrderArr = prettyOrder!=null?prettyOrder.split("[;,]"):new String[0]; for (int i = 0; i < orderArr.length; i++) { String orderParam = orderArr[i].trim(); Object value = (getMapValue(orderParam, parameters) == null) ? null : getMapValue(orderParam, parameters); if(value != null) { //if pretty name is passed using it as a key value in the ordered map if (prettyOrderArr.length > i) prettyVariableNamesMap.put(orderArr[i].trim(), prettyOrderArr[i].trim()); else prettyVariableNamesMap.put(orderArr[i].trim(), orderArr[i].trim()); orderedMap.put(orderArr[i].trim(), value); } } } for (Entry<String, Object> param : parameters.entrySet()) { if(!orderedMap.containsKey(param.getKey())) { orderedMap.put(param.getKey(), param.getValue()); prettyVariableNamesMap.put(param.getKey(), param.getKey()); } } StringBuffer filesLinks = new StringBuffer(); // Saving the form in the database and the submitted file to the dotCMS String formType = getMapValue("formType", parameters) != null? (String)getMapValue("formType", parameters):(String)getMapValue("formName", parameters); WebForm formBean = saveFormBean(parameters, host, formType, ignoreString, filesLinks); // Setting up the email // Email variables - decrypting crypted email addresses String from = UtilMethods.replace((String)getMapValue("from", parameters), "spamx", ""); String to = UtilMethods.replace((String)getMapValue("to", parameters), "spamx", ""); String cc = UtilMethods.replace((String)getMapValue("cc", parameters), "spamx", ""); String bcc = UtilMethods.replace((String)getMapValue("bcc", parameters), "spamx", ""); String fromName = UtilMethods.replace((String)getMapValue("fromName", parameters), "spamx", ""); try { from = PublicEncryptionFactory.decryptString(from); } catch (Exception e) { } try { to = PublicEncryptionFactory.decryptString(to); } catch (Exception e) { } try { cc = PublicEncryptionFactory.decryptString(cc); } catch (Exception e) { } try { bcc = PublicEncryptionFactory.decryptString(bcc); } catch (Exception e) { } try { fromName = PublicEncryptionFactory.decryptString(fromName); } catch (Exception e) { } String subject = (String)getMapValue("subject", parameters); subject = (subject == null) ? "Mail from " + host.getHostname() + "" : subject; String emailFolder = (String)getMapValue("emailFolder", parameters); boolean html = getMapValue("html", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("html", parameters)):true; String templatePath = (String) getMapValue("emailTemplate", parameters); // Building email message no template Map<String, String> emailBodies = null; try { emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user); } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: Couldn't build the email body text.", e); throw new DotRuntimeException("sendForm: Couldn't build the email body text.", e); } // Saving email backup in a file try { String filePath = FileUtil.getRealPath(Config.getStringProperty("EMAIL_BACKUPS")); new File(filePath).mkdir(); File file = null; synchronized (emailTime) { emailTime = new Long(emailTime.longValue() + 1); if (UtilMethods.isSet(emailFolder)) { new File(filePath + File.separator + emailFolder).mkdir(); filePath = filePath + File.separator + emailFolder; } file = new File(filePath + File.separator + emailTime.toString() + ".html"); } if (file != null) { java.io.OutputStream os = new java.io.FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os); if(emailBodies.get("emailHTMLBody") != null) bos.write(emailBodies.get("emailHTMLBody").getBytes()); else if(emailBodies.get("emailHTMLTableBody") != null) bos.write(emailBodies.get("emailHTMLTableBody").getBytes()); else bos.write(emailBodies.get("emailPlainTextBody").getBytes()); bos.flush(); bos.close(); os.close(); } } catch (Exception e) { Logger.warn(EmailFactory.class, "sendForm: Couldn't save the email backup in " + Config.getStringProperty("EMAIL_BACKUPS")); } // send the mail out; Mailer m = new Mailer(); m.setToEmail(to); m.setFromEmail(from); m.setFromName(fromName); m.setCc(cc); m.setBcc(bcc); m.setSubject(subject); if (html) { if(UtilMethods.isSet(emailBodies.get("emailHTMLBody"))) m.setHTMLBody(emailBodies.get("emailHTMLBody")); else m.setHTMLBody(emailBodies.get("emailHTMLTableBody")); } m.setTextBody(emailBodies.get("emailPlainTextBody")); //Attaching files requested to be attached to the email if(attachFiles != null) { attachFiles = "," + attachFiles.replaceAll("\\s", "") + ","; for(Entry<String, Object> entry : parameters.entrySet()) { if(entry.getValue() instanceof File && attachFiles.indexOf("," + entry.getKey() + ",") > -1) { File f = (File)entry.getValue(); m.addAttachment(f, entry.getKey() + "." + UtilMethods.getFileExtension(f.getName())); } } } if (m.sendMessage()) { // there is an auto reply, send it on if ((UtilMethods.isSet((String)getMapValue("autoReplyTemplate", parameters)) || UtilMethods.isSet((String)getMapValue("autoReplyText", parameters))) && UtilMethods.isSet((String)getMapValue("autoReplySubject", parameters)) && UtilMethods.isSet((String)getMapValue("autoReplyFrom", parameters))) { templatePath = (String) getMapValue("autoReplyTemplate", parameters); if(UtilMethods.isSet(templatePath)) { try { emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user); } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: Couldn't build the auto reply email body text. Sending plain text.", e); } } m = new Mailer(); String autoReplyTo = (String)(getMapValue("autoReplyTo", parameters) == null?getMapValue("from", parameters):getMapValue("autoReplyTo", parameters)); m.setToEmail(UtilMethods.replace(autoReplyTo, "spamx", "")); m.setFromEmail(UtilMethods.replace((String)getMapValue("autoReplyFrom", parameters), "spamx", "")); m.setSubject((String)getMapValue("autoReplySubject", parameters)); String autoReplyText = (String)getMapValue("autoReplyText", parameters); boolean autoReplyHtml = getMapValue("autoReplyHtml", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("autoReplyHtml", parameters)):html; if (autoReplyText != null) { if(autoReplyHtml) { m.setHTMLBody((String)getMapValue("autoReplyText", parameters)); } else { m.setTextBody((String)getMapValue("autoReplyText", parameters)); } } else { if (autoReplyHtml) { if(UtilMethods.isSet(emailBodies.get("emailHTMLBody"))) m.setHTMLBody(emailBodies.get("emailHTMLBody")); else m.setHTMLBody(emailBodies.get("emailHTMLTableBody")); } m.setTextBody(emailBodies.get("emailPlainTextBody")); } m.sendMessage(); } } else { if(formBean != null){ try { HibernateUtil.delete(formBean); } catch (DotHibernateException e) { Logger.error(EmailFactory.class, e.getMessage(), e); } } throw new DotRuntimeException("Unable to send the email"); } return formBean; } public static Map<String, String> buildEmail(String templatePath, Host host, Map<String,Object> parameters, Map<String, String> prettyParametersNamesMap, String filesLinks, String ignoreString, User user) throws WebAssetException, ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, DotDataException, DotSecurityException, PortalException, SystemException { StringBuffer emailHTMLBody = new StringBuffer(); StringBuffer emailHTMLTableBody = new StringBuffer(); StringBuffer emailPlainTextBody = new StringBuffer(); //Case when a html page template is passed as parameter if(UtilMethods.isSet(templatePath)) { Identifier id = APILocator.getIdentifierAPI().find(host,templatePath); String idInode = id.getInode(); String languageId = Long.toString((APILocator.getLanguageAPI().getDefaultLanguage().getId())); try { if(UtilMethods.isSet(parameters.get("languageId"))) { languageId = (String) parameters.get("languageId"); } } catch(ClassCastException e) { Logger.info(EmailFactory.class, "Error parsing languageId"); } String languageStr = "_" + languageId; Template t = null; try { if(InodeUtils.isSet(idInode)) { t = UtilMethods.getVelocityTemplate("live/"+ idInode + languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION")); } else { t = UtilMethods.getVelocityTemplate(templatePath); } } catch (Exception e) { } if (t != null) { HttpServletRequest request = (HttpServletRequest) parameters.get("request"); HttpServletResponse response = (HttpServletResponse) parameters.get("response"); Context context = null; if(InodeUtils.isSet(idInode) && request != null && response != null) { context = VelocityUtil.getWebContext(request,response); } else { context = VelocityUtil.getBasicContext(); } //Copying the parameters to the context for(Entry<String, Object> entry : parameters.entrySet()) { Object value = getMapValue(entry.getKey(), parameters); if(entry.getKey().equals("ccNumber") && value instanceof String) { value = (String)UtilMethods.obfuscateCreditCard((String)value); } if(entry.getKey().contains("cvv") && value instanceof String) { String valueString = (String)value; if(valueString.length() > 3){ value = (String)UtilMethods.obfuscateString(valueString,2); } else { value = (String)UtilMethods.obfuscateString(valueString,1); } } context.put(entry.getKey(), value); } context.put("utilMethods", new UtilMethods()); context.put("UtilMethods", new UtilMethods()); context.put("host", host); if(user != null) context.put("user", user); StringWriter writer = new StringWriter(); //Rendering the html template with the parameters t.merge(context, writer); String textVar = writer.toString(); emailHTMLBody = new StringBuffer(alterBodyHtmlAbsolutizePaths(replaceTextVar(textVar, parameters, user), host.getHostname())); } } String subject = (String)getMapValue("subject", parameters); subject = (subject == null) ? "Mail from " + host.getHostname(): subject; emailHTMLTableBody.append("<html><style>td{font-family:arial;font-size:10pt;}</style><BODY>"); emailHTMLTableBody.append("<TABLE bgcolor=eeeeee width=95%>"); emailHTMLTableBody.append("<TR><TD colspan=2><strong>Information from " + host.getHostname() + ": " + subject + "</strong></TD></TR>"); emailPlainTextBody.append("Information from " + host.getHostname() + ": \t" + subject + "\n\n"); // Loop over the request Map or the ordered Map Iterator<Entry<String,Object>> it = parameters.entrySet().iterator(); while (it.hasNext()) { Entry<String, Object> e = (Entry<String, Object>) it.next(); String key = e.getKey(); Object mapvalue = getMapValue(key, parameters); if (mapvalue instanceof String) { String value = (String)mapvalue; if(key.equals("ccNumber") && value instanceof String) { value = (String)UtilMethods.obfuscateCreditCard((String)value); } if(key.contains("cvv") && value instanceof String) { String valueString = (String)value; if(valueString.length() > 3){ value = (String)UtilMethods.obfuscateString(valueString,2); } else { value = (String)UtilMethods.obfuscateString(valueString,1); } } if (ignoreString.indexOf(":" + key + ":") < 0 && UtilMethods.isSet(value)) { String prettyKey = prettyParametersNamesMap.get(key); String capKey = prettyKey != null?prettyKey:UtilMethods.capitalize(key); emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap>&nbsp;" + capKey + "&nbsp;</TD>"); emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + value + "</TD></TR>"); emailPlainTextBody.append(capKey + ":\t" + value + "\n"); } } } if (UtilMethods.isSet(filesLinks)) { emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap>&nbsp;Files&nbsp;</TD>"); emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + filesLinks + "</TD></TR>"); emailPlainTextBody.append("Files:\t" + filesLinks + "\n"); } emailHTMLTableBody.append("</TABLE></BODY></HTML>"); Map<String, String> returnMap = new HashMap<String, String>(); if(UtilMethods.isSet(emailHTMLBody.toString())) returnMap.put("emailHTMLBody", emailHTMLBody.toString()); if(UtilMethods.isSet(emailHTMLTableBody.toString())) returnMap.put("emailHTMLTableBody", emailHTMLTableBody.toString()); returnMap.put("emailPlainTextBody", emailPlainTextBody.toString()); return returnMap; } private static WebForm saveFormBean (Map<String, Object> parameters, Host host, String formType, String ignoreString, StringBuffer filesLinks) { //Fields predefined for the form reports String predefinedFields = ":prefix:title:firstName:middleInitial:middleName:lastName:fullName:organization:address:address1:address2:city:state:zip:country:phone:email:"; //Return variable WebForm formBean = new WebForm(); formBean.setFormType(formType); // Copy the common fields set in the form try { for (Entry<String, Object> param : parameters.entrySet()) { BeanUtils.setProperty(formBean, param.getKey(), getMapValue(param.getKey(), parameters)); } } catch (Exception e1) { Logger.error(EmailFactory.class, "sendForm: Error ocurred trying to copy the form bean parameters", e1); } try { HibernateUtil.save(formBean); } catch (DotHibernateException e) { Logger.error(EmailFactory.class, e.getMessage(), e); } String formId = formBean.getWebFormId(); // Loop over the request Map or the ordered Map to set the custom // fields and also saving the submitted files StringBuffer customFields = new StringBuffer(); Set<Entry<String, Object>> paramSet = parameters.entrySet(); for (Entry<String, Object> param : paramSet) { String key = (String) param.getKey(); String value = null; Object paramValue = getMapValue(key, parameters); if (paramValue instanceof File) { File f = (File) param.getValue(); String submittedFileName = f.getName(); String fileName = key + "." + UtilMethods.getFileExtension(submittedFileName); if(getMapValue(fileName.substring(4, key.length()) + "FName", parameters) != null) { fileName = getMapValue(fileName.substring(4, key.length()) + "FName", parameters) + "." + UtilMethods.getFileExtension(submittedFileName); } //Saving the file try { if(f.exists()) { String filesFolder = getMapValue("formFolder", parameters) instanceof String?(String)getMapValue("formFolder", parameters):null; String fileLink = saveFormFile(formId, formType, fileName, f, host, filesFolder); filesLinks.append(filesLinks.toString().equals("")? "http://" + host.getHostname() + fileLink : ",http://" + host.getHostname() + fileLink); } } catch (Exception e) { Logger.error(EmailFactory.class, "sendForm: couldn't saved the submitted file into the cms = " + fileName, e); try { HibernateUtil.delete(formBean); } catch (DotHibernateException e1) { Logger.error(EmailFactory.class, e1.getMessage(), e1); } throw new DotRuntimeException("sendForm: couldn't saved the submitted file into the cms = " + fileName, e); } } else if (paramValue instanceof String) value = (String)paramValue; List<String> cFields = new ArrayList<String>(); if (predefinedFields.indexOf(":" + key + ":") < 0 && ignoreString.indexOf(":" + key + ":") < 0 && UtilMethods.isSet(value)) { value = value.replaceAll("\\|", " ").replaceAll("=", " "); if(key.equals("ccNumber")) value = UtilMethods.obfuscateCreditCard(value); String capKey = UtilMethods.capitalize(key); int aux = 2; String capKeyAux = capKey; while (cFields.contains(capKeyAux)) { capKeyAux = capKey + aux; ++aux; } cFields.add(capKeyAux); String cField = capKeyAux + "=" + value; customFields.append(cField + "|"); } } customFields.append("Files=" + filesLinks); //Setting the custom fields and saving them formBean.setCustomFields(customFields.toString()); formBean.setSubmitDate(new Date()); if(UtilMethods.isSet(formType)){ try { HibernateUtil.saveOrUpdate(formBean); } catch (DotHibernateException e) { throw new DotRuntimeException("Webform Save Failed"); } } else{ Logger.debug(EmailFactory.class, "The web form doesn't have the required formType field, the form data will not be saved in the database."); } return formBean; } private static String getFormFileFolderPath (String formType, String formInode) { String path = Config.getStringProperty("SAVED_UPLOAD_FILES_PATH") + "/" + formType.replace(" ", "_") + "/" + String.valueOf(formInode).substring(0, 1) + "/" + formInode; return path; } private static String saveFormFile (String formInode, String formType, String fileName, File fileToSave, Host currentHost, String filesFolder) throws Exception { FileAPI fileAPI=APILocator.getFileAPI(); String path; if(filesFolder != null) path = filesFolder; else path = getFormFileFolderPath(formType, formInode); Folder folder = APILocator.getFolderAPI().createFolders(path, currentHost, APILocator.getUserAPI().getSystemUser(), false); String baseFilename = fileName; int c = 1; while(fileAPI.fileNameExists(folder, fileName)) { fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename); c++; } Host host = APILocator.getHostAPI().find(folder.getHostId(), APILocator.getUserAPI().getSystemUser(), false); while(APILocator.getFileAssetAPI().fileNameExists(host,folder, fileName, "")) { fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename); c++; } Contentlet cont = new Contentlet(); cont.setStructureInode(folder.getDefaultFileType()); cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(fileName)); cont.setFolder(folder.getInode()); cont.setHost(host.getIdentifier()); cont.setBinary(FileAssetAPI.BINARY_FIELD, fileToSave); APILocator.getContentletAPI().checkin(cont, APILocator.getUserAPI().getSystemUser(),false); return path + "/" + fileName; } private static String replaceTextVar(String template, Map<String, Object> parameters, User user) { String finalMessageStr = template; Set<String> keys = parameters.keySet(); for(String key : keys) { if(getMapValue(key, parameters) instanceof String) { String value = (String)getMapValue(key, parameters); value = (value != null ? value : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/"+ key +"(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))" + key + "(\")?( )*/*( )*(>|(&gt;))",value); } } if(UtilMethods.isSet(user)) { Address address = new Address(); try { List<Address> adds = PublicAddressFactory.getAddressesByUserId(user.getUserId()); if (adds != null && adds.size() > 0) { address = (Address) adds.get(0); } } catch(Exception e) { Logger.error(EmailFactory.class, "Send To Friend Failed" + e); } //Variables replacement from user object finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varName(\")?( )*/*( )*(>|(&gt;))", (user.getFirstName()!=null) ? user.getFirstName() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varEmail(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varEmail(\")?( )*/*( )*(>|(&gt;))", (user.getEmailAddress()!=null) ? user.getEmailAddress() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varMiddleName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varMiddleName(\")?( )*/*( )*(>|(&gt;))", (user.getMiddleName()!=null) ? user.getMiddleName() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varLastName(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varLastName(\")?( )*/*( )*(>|(&gt;))", (user.getLastName()!=null) ? user.getLastName() : ""); UserProxy userproxy; try { userproxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user,APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error(EmailFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varLastMessage(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varLastMessage(\")?( )*/*( )*(>|(&gt;))", (userproxy.getLastMessage()!=null) ? userproxy.getLastMessage() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varAddress1(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varAddress1(\")?( )*/*( )*(>|(&gt;))", (address.getStreet1()!=null) ? address.getStreet1() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varAddress2(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varAddress2(\")?( )*/*( )*(>|(&gt;))", (address.getStreet2()!=null) ? address.getStreet2() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varPhone(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varPhone(\")?( )*/*( )*(>|(&gt;))", (address.getPhone()!=null) ? address.getPhone() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varState(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varState(\")?( )*/*( )*(>|(&gt;))", (address.getState()!=null) ? address.getState() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varCity(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varCity(\")?( )*/*( )*(>|(&gt;))", (address.getCity()!=null) ? address.getCity() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varCountry(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varCountry(\")?( )*/*( )*(>|(&gt;))", (address.getCountry()!=null) ? address.getCountry() : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/varZip(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))varZip(\")?( )*/*( )*(>|(&gt;))", (address.getZip()!=null) ? address.getZip() : ""); //gets default company to get locale Company comp = PublicCompanyFactory.getDefaultCompany(); try { int varCounter = 1; for (;varCounter < 26;varCounter++) { String var = LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + varCounter); if (var!=null) var = var.replaceAll(" ","_"); String value = ""; try { value = BeanUtils.getSimpleProperty(userproxy, "var" + varCounter); } catch (Exception e) { Logger.error(EmailFactory.class, "An error as ocurred trying to access the variable var" + varCounter + " from the user proxy.", e); } finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/"+var+"(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))" + var + "(\")?( )*/*( )*(>|(&gt;))", (value != null) ? value : ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))/var" + varCounter + "(>|(&gt;))", ""); finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(&lt;))var" + varCounter + "(\")?( )*/*( )*(>|(&gt;))", (value != null) ? value : ""); } } catch(LanguageException le) { Logger.error(EmailFactory.class, le.getMessage()); } } return finalMessageStr; } public static Object getMapValue(String key, Map<String, Object> map) { try { try { if(((Object[]) map.get(key)).length > 1) { String returnValue = ""; for(Object object : ((Object[]) map.get(key))) { returnValue += object.toString() + ", "; } returnValue = returnValue.substring(0,returnValue.lastIndexOf(",")); return returnValue; } } catch(Exception ex) {} return ((Object[]) map.get(key))[0]; } catch (Exception e) { try { return (Object) map.get(key); } catch (Exception ex) { return null; } } } }
./CrossVul/dataset_final_sorted/CWE-89/java/bad_5029_1
crossvul-java_data_good_5080_0
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dashbuilder.dataprovider.sql.dialect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.dashbuilder.dataprovider.sql.model.Column; import org.dashbuilder.dataprovider.sql.model.Condition; import org.dashbuilder.dataprovider.sql.model.CoreCondition; import org.dashbuilder.dataprovider.sql.model.CreateTable; import org.dashbuilder.dataprovider.sql.model.Delete; import org.dashbuilder.dataprovider.sql.model.DynamicDateColumn; import org.dashbuilder.dataprovider.sql.model.FixedDateColumn; import org.dashbuilder.dataprovider.sql.model.FunctionColumn; import org.dashbuilder.dataprovider.sql.model.Insert; import org.dashbuilder.dataprovider.sql.model.LogicalCondition; import org.dashbuilder.dataprovider.sql.model.SQLStatement; import org.dashbuilder.dataprovider.sql.model.Select; import org.dashbuilder.dataprovider.sql.model.SimpleColumn; import org.dashbuilder.dataprovider.sql.model.SortColumn; import org.dashbuilder.dataprovider.sql.model.Table; import org.dashbuilder.dataset.ColumnType; import org.dashbuilder.dataset.filter.CoreFunctionType; import org.dashbuilder.dataset.filter.LogicalExprType; import org.dashbuilder.dataset.group.AggregateFunctionType; import org.dashbuilder.dataset.group.DateIntervalType; import org.dashbuilder.dataset.sort.SortOrder; import static org.dashbuilder.dataprovider.sql.SQLFactory.*; public class DefaultDialect implements Dialect { private static final String AND = " AND "; @Override public String[] getExcludedColumns() { return new String[] {}; } @Override public String getColumnSQL(Column column) { if (column instanceof FunctionColumn) { return getFunctionColumnSQL((FunctionColumn) column); } else if (column instanceof SortColumn) { return getSortColumnSQL((SortColumn) column); } else if (column instanceof DynamicDateColumn) { return getDynamicDateColumnSQL((DynamicDateColumn) column); } else if (column instanceof FixedDateColumn) { return getFixedDateColumnSQL((FixedDateColumn) column); } else if (column instanceof SimpleColumn) { return getSimpleColumnSQL((SimpleColumn) column); } else { return getColumnNameSQL(column.getName()); } } @Override public String getColumnTypeSQL(Column column) { switch (column.getType()) { case NUMBER: { return "NUMERIC(28,2)"; } case DATE: { return "TIMESTAMP"; } default: { return "VARCHAR(" + column.getLength() + ")"; } } } @Override public String convertToString(Object value) { try { return value == null ? null : (String) value; } catch (ClassCastException e) { return value.toString(); } } @Override public Double convertToDouble(Object value) { try { return value == null ? null : ((Number) value).doubleValue(); } catch (ClassCastException e) { return Double.parseDouble(value.toString()); } } @Override public Date convertToDate(Object value) { try { return value == null ? null : (Date) value; } catch (ClassCastException e) { throw new IllegalArgumentException("Not a java.util.Date: " + value + " (" + value.getClass().getName() + ")"); } } @Override public String getTableSQL(SQLStatement<?> stmt) { Table table = stmt.getTable(); String name = getTableNameSQL(table.getName()); if (StringUtils.isBlank(table.getSchema())) { return name; } else{ return getSchemaNameSQL(table.getSchema()) + "." + name; } } @Override public String getTableNameSQL(String name) { return name; } @Override public String getSchemaNameSQL(String name) { return name; } @Override public String getSimpleColumnSQL(SimpleColumn column) { String result = getColumnNameSQL(column.getName()); if (column.getFunctionType() != null) { result = getColumnFunctionSQL(result, column.getFunctionType()); } return result; } @Override public String getFunctionColumnSQL(FunctionColumn column) { if (FunctionColumn.LOWER.equals(column.getFunction())) { return getLowerFunctionSQL(column.getColumns()[0]); } if (FunctionColumn.CONCAT.equals(column.getFunction())) { return getConcatFunctionSQL(column.getColumns()); } if (FunctionColumn.YEAR.equals(column.getFunction())) { return getDatePartFunctionSQL("YEAR", column.getColumns()[0]); } if (FunctionColumn.MONTH.equals(column.getFunction())) { return getDatePartFunctionSQL("MONTH", column.getColumns()[0]); } if (FunctionColumn.DAY.equals(column.getFunction())) { return getDatePartFunctionSQL("DAY", column.getColumns()[0]); } if (FunctionColumn.HOUR.equals(column.getFunction())) { return getDatePartFunctionSQL("HOUR", column.getColumns()[0]); } if (FunctionColumn.MINUTE.equals(column.getFunction())) { return getDatePartFunctionSQL("MINUTE", column.getColumns()[0]); } if (FunctionColumn.SECOND.equals(column.getFunction())) { return getDatePartFunctionSQL("SECOND", column.getColumns()[0]); } throw new IllegalArgumentException("Column function not supported: " + column.getFunction()); } @Override public String getLowerFunctionSQL(Column column) { String columnSQL = getColumnSQL(column); return "LOWER(" + columnSQL + ")"; } @Override public String getConcatFunctionSQL(Column[] columns) { return getConcatFunctionSQL(columns, "(", ")", " || "); } public String getConcatFunctionSQL(Column[] columns, String begin, String end, String separator) { StringBuilder out = new StringBuilder(); out.append(begin); for (int i = 0; i < columns.length; i++) { if (i > 0) out.append(separator); Column column = columns[i]; ColumnType type = column.getType(); if (ColumnType.LABEL.equals(type) || ColumnType.TEXT.equals(type)) { out.append("'").append(column.getName()).append("'"); } else { // Cast needed out.append(getColumnCastSQL(column)); } } out.append(end); return out.toString(); } public String getColumnCastSQL(Column column) { String columnSQL = getColumnSQL(column); return "CAST(" + columnSQL + " AS VARCHAR)"; } @Override public String getDatePartFunctionSQL(String part, Column column) { String columnSQL = getColumnSQL(column); return "EXTRACT(" + part + " FROM " + columnSQL + ")"; } @Override public String getSortColumnSQL(SortColumn sortColumn) { Column column = sortColumn.getSource(); String columnSQL = getColumnSQL(column); // Always order by the alias (if any) if (!StringUtils.isBlank(column.getAlias())) { columnSQL = getAliasForStatementSQL(column.getAlias()); } return columnSQL + " " + getSortOrderSQL(sortColumn.getOrder()); } @Override public String getSortOrderSQL(SortOrder order) { if (SortOrder.ASCENDING.equals(order)) { return "ASC"; } if (SortOrder.DESCENDING.equals(order)) { return "DESC"; } throw new IllegalArgumentException("Sort order not supported: " + order); } /** * The text conversion of a date column is very DB specific. * A mechanism combining concat and extract functions is used by default. * Depending on the DB dialect a more polished approach can be used. * For instance, <ul> * <li>In Oracle and Postgres the 'to_char' function is used.</li> * <li>In Mysql, 'date_format'</li> * <li>In H2, the 'to_char' function is not used as it's only available since version 1.3.175 and we do need to support older versions.</li> * </ul> */ @Override public String getDynamicDateColumnSQL(DynamicDateColumn column) { Column dateColumn = toChar(column); return getColumnSQL(dateColumn); } public Column toChar(DynamicDateColumn column) { Column target = column(column.getName()); DateIntervalType type = column.getDateType(); Column SEPARATOR_DATE = column("-", ColumnType.TEXT, 3); Column SEPARATOR_EMPTY = column(" ", ColumnType.TEXT, 3); Column SEPARATOR_TIME = column(":", ColumnType.TEXT, 3); if (DateIntervalType.SECOND.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour(), SEPARATOR_TIME, target.minute(), SEPARATOR_TIME, target.second()); } if (DateIntervalType.MINUTE.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour(), SEPARATOR_TIME, target.minute()); } if (DateIntervalType.HOUR.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day(), SEPARATOR_EMPTY, target.hour()); } if (DateIntervalType.DAY.equals(type) || DateIntervalType.WEEK.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month(), SEPARATOR_DATE, target.day()); } if (DateIntervalType.MONTH.equals(type) || DateIntervalType.QUARTER.equals(type)) { return concat(target.year(), SEPARATOR_DATE, target.month()); } if (DateIntervalType.YEAR.equals(type) || DateIntervalType.DECADE.equals(type) || DateIntervalType.CENTURY.equals(type) || DateIntervalType.MILLENIUM.equals(type)) { return target.year(); } throw new IllegalArgumentException("Group '" + target.getName() + "' by the given date interval type is not supported: " + type); } @Override public String getFixedDateColumnSQL(FixedDateColumn column) { Column target = column(column.getName()); DateIntervalType type = column.getDateType(); if (DateIntervalType.SECOND.equals(type)) { return getColumnSQL(target.second()); } if (DateIntervalType.MINUTE.equals(type)) { return getColumnSQL(target.minute()); } if (DateIntervalType.HOUR.equals(type)) { return getColumnSQL(target.hour()); } if (DateIntervalType.DAY_OF_WEEK.equals(type)) { return getColumnSQL(target.day()); } if (DateIntervalType.MONTH.equals(type)) { return getColumnSQL(target.month()); } if (DateIntervalType.QUARTER.equals(type)) { // Emulated using month and converted to quarter during the data set post-processing return getColumnSQL(target.month()); } throw new IllegalArgumentException("Interval size '" + type + "' not supported for " + "fixed date intervals. The only supported sizes are: " + StringUtils.join(DateIntervalType.FIXED_INTERVALS_SUPPORTED, ",")); } @Override public String getColumnNameSQL(String name) { return name; } @Override public String getColumnNameQuotedSQL(String name) { return "\"" + name + "\""; } @Override public String getAliasForColumnSQL(String alias) { return "\"" + alias + "\""; } @Override public String getAliasForStatementSQL(String alias) { return "\"" + alias + "\""; } @Override public String getConditionSQL(Condition condition) { if (condition instanceof CoreCondition) { return getCoreConditionSQL((CoreCondition) condition); } if (condition instanceof LogicalCondition) { return getLogicalConditionSQL((LogicalCondition) condition); } throw new IllegalArgumentException("Condition type not supported: " + condition); } @Override public String getCoreConditionSQL(CoreCondition condition) { String columnSQL = getColumnSQL(condition.getColumn()); CoreFunctionType type = condition.getFunction(); Object[] params = condition.getParameters(); if (CoreFunctionType.IS_NULL.equals(type)) { return getIsNullConditionSQL(columnSQL); } if (CoreFunctionType.NOT_NULL.equals(type)) { return getNotNullConditionSQL(columnSQL); } if (CoreFunctionType.EQUALS_TO.equals(type)) { return getIsEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_EQUALS_TO.equals(type)) { return getNotEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_EQUALS_TO.equals(type)) { return getNotEqualsToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LIKE_TO.equals(type)) { return getLikeToConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.GREATER_THAN.equals(type)) { return getGreaterThanConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.GREATER_OR_EQUALS_TO.equals(type)) { return getGreaterOrEqualsConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LOWER_THAN.equals(type)) { return getLowerThanConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.LOWER_OR_EQUALS_TO.equals(type)) { return getLowerOrEqualsConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.BETWEEN.equals(type)) { return getBetweenConditionSQL(columnSQL, params[0], params[1]); } if (CoreFunctionType.IN.equals(type)) { return getInConditionSQL(columnSQL, params[0]); } if (CoreFunctionType.NOT_IN.equals(type)) { return getNotInConditionSQL(columnSQL, params[0]); } throw new IllegalArgumentException("Core condition type not supported: " + type); } @Override public String getNotNullConditionSQL(String column) { return column + " IS NOT NULL"; } @Override public String getIsNullConditionSQL(String column) { return column + " IS NULL"; } @Override public String getIsEqualsToConditionSQL(String column, Object param) { if (param == null) { return getIsNullConditionSQL(column); } else { String paramStr = getParameterSQL(param); return column + " = " + paramStr; } } @Override public String getNotEqualsToConditionSQL(String column, Object param) { if (param == null) { return getNotNullConditionSQL(column); } else { String paramStr = getParameterSQL(param); return column + " <> " + paramStr; } } @Override public String getLikeToConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " LIKE " + paramStr; } @Override public String getGreaterThanConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " > " + paramStr; } @Override public String getGreaterOrEqualsConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " >= " + paramStr; } @Override public String getLowerThanConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " < " + paramStr; } @Override public String getLowerOrEqualsConditionSQL(String column, Object param) { String paramStr = getParameterSQL(param); return column + " <= " + paramStr; } @Override public String getBetweenConditionSQL(String column, Object from, Object to) { String fromStr = getParameterSQL(from); String toStr = getParameterSQL(to); return column + " BETWEEN " + fromStr + AND + toStr; } @Override public String getInConditionSQL(String column, Object param) { StringBuilder inStatement = new StringBuilder(); inStatement.append(column); inStatement.append(" IN ("); for (Object p : (Collection<?>) param) { inStatement.append(getParameterSQL(p) + ","); } inStatement.deleteCharAt(inStatement.length()-1); inStatement.append(")"); return inStatement.toString(); } @Override public String getNotInConditionSQL(String column, Object param) { StringBuilder inStatement = new StringBuilder(); inStatement.append(column); inStatement.append(" NOT IN ("); for (Object p : (Collection<?>) param) { inStatement.append(getParameterSQL(p) + ","); } inStatement.deleteCharAt(inStatement.length()-1); inStatement.append(")"); return inStatement.toString(); } @Override public String getParameterSQL(Object param) { if (param == null) { return "null"; } if (param instanceof Number) { return getNumberParameterSQL((Number) param); } if (param instanceof Date) { return getDateParameterSQL((Date) param); } return getStringParameterSQL(param.toString()); } @Override public String getNumberParameterSQL(Number param) { return param.toString(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); @Override public String getDateParameterSQL(Date param) { // timestamp '2015-08-24 13:14:36.615' return "TIMESTAMP '" + dateFormat.format(param) + "'"; } @Override public String getStringParameterSQL(String param) { // DASHBUILDE-113: SQL Injection on data set lookup filters String escapedParam = param.replaceAll("'", "''"); return "'" + escapedParam + "'"; } @Override public String getLogicalConditionSQL(LogicalCondition condition) { LogicalExprType type = condition.getType(); Condition[] conditions = condition.getConditions(); if (LogicalExprType.NOT.equals(type)) { return getNotExprConditionSQL(conditions[0]); } if (LogicalExprType.AND.equals(type)) { return getAndExprConditionSQL(conditions); } if (LogicalExprType.OR.equals(type)) { return getOrExprConditionSQL(conditions); } throw new IllegalArgumentException("Logical condition type not supported: " + type); } @Override public String getNotExprConditionSQL(Condition condition) { String conditionSQL = getConditionSQL(condition); return "NOT(" + conditionSQL + ")"; } @Override public String getAndExprConditionSQL(Condition[] conditions) { return _getLogicalExprConditionSQL(conditions, "AND"); } @Override public String getOrExprConditionSQL(Condition[] conditions) { return _getLogicalExprConditionSQL(conditions, "OR"); } protected String _getLogicalExprConditionSQL(Condition[] conditions, String op) { StringBuilder out = new StringBuilder(); out.append("("); for (int i = 0; i < conditions.length; i++) { Condition condition = conditions[i]; String conditionSQL = getConditionSQL(condition); if (i > 0) { out.append(" ").append(op).append(" "); } out.append(conditionSQL); } out.append(")"); return out.toString(); } @Override public String getColumnFunctionSQL(String column, AggregateFunctionType function) { switch (function) { case SUM: { return "SUM(" + column + ")"; } case MAX: { return "MAX(" + column + ")"; } case MIN: { return "MIN(" + column + ")"; } case AVERAGE: { return "AVG(" + column + ")"; } case COUNT: { return "COUNT(" + column + ")"; } case DISTINCT: { return "COUNT(DISTINCT " + column + ")"; } default: { throw new IllegalArgumentException("Function type not valid: " + function); } } } @Override public String getCountQuerySQL(Select select) { List<SortColumn> sortColumns = new ArrayList<SortColumn>(); sortColumns.addAll(select.getOrderBys()); try { // Remove ORDER BY for better performance select.getOrderBys().clear(); return "SELECT " + getColumnFunctionSQL("*", AggregateFunctionType.COUNT) + " FROM (" + select.getSQL() + ") " + getAliasForColumnSQL("dbSQL"); } finally { select.orderBy(sortColumns); } } @Override public String getSQL(CreateTable create) { StringBuilder sql = new StringBuilder("CREATE TABLE "); List<String> pkeys = new ArrayList<String>(); String tname = getTableSQL(create); sql.append(tname); // Columns boolean first = true; sql.append(" (\n"); for (Column column : create.getColumns()) { if (!first) { sql.append(",\n"); } String name = getColumnNameSQL(column.getName()); String type = getColumnTypeSQL(column); sql.append(" ").append(name).append(" ").append(type); if (create.getPrimaryKeys().contains(column)) { sql.append(" NOT NULL"); pkeys.add(name); } first = false; } if (!create.getPrimaryKeys().isEmpty()) { sql.append(",\n"); sql.append(" PRIMARY KEY("); sql.append(StringUtils.join(pkeys, ",")); sql.append(")\n"); } sql.append(")"); return sql.toString(); } @Override public String getSQL(Select select) { // Select clause StringBuilder sql = new StringBuilder(); String selectClause = getSelectSQL(select); sql.append(selectClause); // From clause (inner SQL or table) sql.append(" ").append(getFromSQL(select)); // Where clauses List<Condition> wheres = select.getWheres(); if (!wheres.isEmpty()) { sql.append(" ").append(getWhereSQL(select)); } // Group by List<Column> groupBys = select.getGroupBys(); if (!groupBys.isEmpty()) { sql.append(" ").append(getGroupBySQL(select)); } // Order by List<SortColumn> orderBys = select.getOrderBys(); if (!orderBys.isEmpty()) { sql.append(" ").append(getOrderBySQL(select)); } // Limits int limit = select.getLimit(); int offset = select.getOffset(); if (limit > 0 || offset > 0) { String limitSql = getOffsetLimitSQL(select); if (!StringUtils.isBlank(limitSql)) { sql.append(limitSql); } } return sql.toString(); } @Override public String getSQL(Insert insert) { // Insert clause StringBuilder sql = new StringBuilder(); String insertClause = getInsertStatement(insert); sql.append(insertClause); // Table sql.append(" ").append(getTableSQL(insert)); // Columns boolean first = true; sql.append(" ("); for (Column column : insert.getColumns()) { if (!first) { sql.append(","); } String str = getColumnSQL(column); sql.append(str); first = false; } sql.append(")"); // Values first = true; sql.append(" VALUES ("); for (Object value : insert.getValues()) { if (!first) { sql.append(","); } String str = getParameterSQL(value); sql.append(str); first = false; } sql.append(")"); return sql.toString(); } @Override public String getSQL(Delete delete) { // Delete clause StringBuilder sql = new StringBuilder(); String deleteClause = getDeleteStatement(delete); sql.append(deleteClause); // From clause sql.append(" ").append(getTableSQL(delete)); // Where clauses List<Condition> wheres = delete.getWheres(); if (!wheres.isEmpty()) { sql.append(" ").append(getWhereSQL(delete)); } return sql.toString(); } @Override public String getSelectSQL(Select select) { StringBuilder clause = new StringBuilder(); clause.append(getSelectStatement(select)); clause.append(" "); if (select.getColumns().isEmpty()) { clause.append("*"); } else { boolean first = true; for (Column column : select.getColumns()) { if (!first) { clause.append(", "); } String str = getColumnSQL(column); boolean aliasNonEmpty = !StringUtils.isBlank(column.getAlias()); boolean isSimpleColumn = (column instanceof SimpleColumn) && !str.equals(getColumnNameSQL(column.getAlias())); if (aliasNonEmpty && (allowAliasInStatements() || isSimpleColumn)) { str += " " + getAliasForColumnSQL(column.getAlias()); } clause.append(str); first = false; } } return clause.toString(); } @Override public String getFromSQL(Select select) { String fromSelect = select.getFromSelect(); Table fromTable = select.getFromTable(); String from = getFromStatement(select); if (fromSelect != null) { String alias = getAliasForColumnSQL("dbSQL"); return from + " (" + fromSelect + ") " + alias; } else if (fromTable != null ){ String table = getTableSQL(select); return from + " " + table; } return ""; } @Override public String getWhereSQL(Select select) { StringBuilder sql = new StringBuilder(); List<Condition> wheres = select.getWheres(); boolean first = true; for (Condition condition : wheres) { if (first) { sql.append(getWhereStatement(select)).append(" "); } else { sql.append(AND); } String str = getConditionSQL(condition); sql.append(str); first = false; } return sql.toString(); } @Override public String getWhereSQL(Delete delete) { StringBuilder sql = new StringBuilder(); List<Condition> wheres = delete.getWheres(); boolean first = true; for (Condition condition : wheres) { if (first) { sql.append(getWhereStatement(delete)).append(" "); } else { sql.append(AND); } String str = getConditionSQL(condition); sql.append(str); first = false; } return sql.toString(); } @Override public String getGroupBySQL(Select select) { StringBuilder sql = new StringBuilder(); List<Column> groupBys = select.getGroupBys(); boolean first = true; for (Column column : groupBys) { if (first) { sql.append(getGroupByStatement(select)).append(" "); } else { sql.append(", "); } Column aliasColumn = allowAliasInStatements() ? getAliasStatement(select, column) : null; sql.append(aliasColumn != null ? getAliasForStatementSQL(aliasColumn.getAlias()) : getColumnSQL(column)); first = false; } return sql.toString(); } @Override public String getOrderBySQL(Select select) { StringBuilder sql = new StringBuilder(); List<SortColumn> orderBys = select.getOrderBys(); boolean first = true; for (SortColumn column : orderBys) { if (first) { sql.append(getOrderByStatement(select)).append(" "); } else { sql.append(", "); } Column aliasColumn = allowAliasInStatements() ? getAliasStatement(select, column.getSource()) : null; if (aliasColumn != null) { column = new SortColumn(aliasColumn, column.getOrder()); } String str = getSortColumnSQL(column); sql.append(str); first = false; } return sql.toString(); } @Override public String getOffsetLimitSQL(Select select) { int offset = select.getOffset(); int limit = select.getLimit(); StringBuilder out = new StringBuilder(); if (limit > 0) out.append(" LIMIT ").append(limit); if (offset > 0) out.append(" OFFSET ").append(offset); return out.toString(); } @Override public String getSelectStatement(Select select) { return "SELECT"; } @Override public String getInsertStatement(Insert insert) { return "INSERT INTO"; } @Override public String getDeleteStatement(Delete delete) { return "DELETE FROM"; } @Override public String getFromStatement(Select select) { return "FROM"; } @Override public String getWhereStatement(Select select) { return "WHERE"; } @Override public String getWhereStatement(Delete delete) { return "WHERE"; } @Override public String getGroupByStatement(Select select) { return "GROUP BY"; } @Override public String getOrderByStatement(Select select) { return "ORDER BY"; } // Helper methods protected Object invokeMethod(Object o, String methodName, Object[] params) { Method methods[] = o.getClass().getMethods(); for (int i = 0; i < methods.length; ++i) { if (methodName.equals(methods[i].getName())) { try { methods[i].setAccessible(true); return methods[i].invoke(o, params); } catch (IllegalAccessException ex) { return null; } catch (InvocationTargetException ite) { return null; } } } return null; } public boolean areEquals(Column column1, Column column2) { if (!column1.getName().equals(column2.getName())) { return false; } if (!column1.getClass().getName().equals(column2.getClass().getName())) { return false; } if (column1 instanceof DynamicDateColumn) { DynamicDateColumn dd1 = (DynamicDateColumn) column1; DynamicDateColumn dd2 = (DynamicDateColumn) column2; if (!dd1.getDateType().equals(dd2.getDateType())) { return false; } } if (column1 instanceof FixedDateColumn) { FixedDateColumn fd1 = (FixedDateColumn) column1; FixedDateColumn fd2 = (FixedDateColumn) column2; if (!fd1.getDateType().equals(fd2.getDateType())) { return false; } } return true; } public boolean allowAliasInStatements() { return false; } public Column getAliasStatement(Select select, Column target) { for (Column column : select.getColumns()) { if (!(column instanceof SimpleColumn) && !StringUtils.isBlank(column.getAlias()) && areEquals(column, target)) { return column; } } return null; } }
./CrossVul/dataset_final_sorted/CWE-89/java/good_5080_0
crossvul-java_data_bad_4334_2
/* * Copyright (C) 2013, 2014, 2017, 2018, 2020 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 23. December 2013 by Joerg Schaible */ package com.thoughtworks.acceptance; import java.beans.EventHandler; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.security.AnyTypePermission; import com.thoughtworks.xstream.security.ForbiddenClassException; import com.thoughtworks.xstream.security.NoTypePermission; /** * @author J&ouml;rg Schaible */ public class SecurityVulnerabilityTest extends AbstractAcceptanceTest { private final static StringBuffer BUFFER = new StringBuffer(); protected void setUp() throws Exception { super.setUp(); BUFFER.setLength(0); xstream.alias("runnable", Runnable.class); } protected void setupSecurity(XStream xstream) { } public void testCannotInjectEventHandler() { final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; try { xstream.fromXML(xml); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName()) > 0); } assertEquals(0, BUFFER.length()); } public void testCannotInjectEventHandlerWithUnconfiguredSecurityFramework() { xstream.alias("runnable", Runnable.class); final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; try { xstream.fromXML(xml); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName())>=0); } assertEquals(0, BUFFER.length()); } public void testExplicitlyConvertEventHandler() { final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; xstream.allowTypes(new Class[]{EventHandler.class}); xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream .getReflectionProvider(), EventHandler.class)); final Runnable[] array = (Runnable[])xstream.fromXML(xml); assertEquals(0, BUFFER.length()); array[0].run(); assertEquals("Executed!", BUFFER.toString()); } public static class Exec { public void exec() { BUFFER.append("Executed!"); } } public void testInstanceOfVoid() { try { xstream.fromXML("<void/>"); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { assertEquals("void", e.get("construction-type")); } } public void testDeniedInstanceOfVoid() { xstream.addPermission(AnyTypePermission.ANY); // clear out defaults xstream.denyTypes(new Class[] { void.class, Void.class }); try { xstream.fromXML("<void/>"); fail("Thrown " + ForbiddenClassException.class.getName() + " expected"); } catch (final ForbiddenClassException e) { // OK } } public void testAllowedInstanceOfVoid() { xstream.allowTypes(new Class[] { void.class, Void.class }); try { xstream.fromXML("<void/>"); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { assertEquals("void", e.get("construction-type")); } } public static class LazyIterator { } public void testInstanceOfLazyIterator() { xstream.alias("lazy-iterator", LazyIterator.class); try { xstream.fromXML("<lazy-iterator/>"); fail("Thrown " + ForbiddenClassException.class.getName() + " expected"); } catch (final ForbiddenClassException e) { // OK } } }
./CrossVul/dataset_final_sorted/CWE-78/java/bad_4334_2
crossvul-java_data_bad_4334_1
/* * Copyright (C) 2003, 2004, 2005, 2006 Joe Walnes. * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2020 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 26. September 2003 by Joe Walnes */ package com.thoughtworks.xstream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Pattern; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.ConverterRegistry; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.BigDecimalConverter; import com.thoughtworks.xstream.converters.basic.BigIntegerConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.ByteConverter; import com.thoughtworks.xstream.converters.basic.CharConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.basic.DoubleConverter; import com.thoughtworks.xstream.converters.basic.FloatConverter; import com.thoughtworks.xstream.converters.basic.IntConverter; import com.thoughtworks.xstream.converters.basic.LongConverter; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.basic.ShortConverter; import com.thoughtworks.xstream.converters.basic.StringBufferConverter; import com.thoughtworks.xstream.converters.basic.StringConverter; import com.thoughtworks.xstream.converters.basic.URIConverter; import com.thoughtworks.xstream.converters.basic.URLConverter; import com.thoughtworks.xstream.converters.collections.ArrayConverter; import com.thoughtworks.xstream.converters.collections.BitSetConverter; import com.thoughtworks.xstream.converters.collections.CharArrayConverter; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.converters.collections.SingletonCollectionConverter; import com.thoughtworks.xstream.converters.collections.SingletonMapConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.converters.collections.TreeSetConverter; import com.thoughtworks.xstream.converters.extended.ColorConverter; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.FileConverter; import com.thoughtworks.xstream.converters.extended.FontConverter; import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter; import com.thoughtworks.xstream.converters.extended.JavaClassConverter; import com.thoughtworks.xstream.converters.extended.JavaFieldConverter; import com.thoughtworks.xstream.converters.extended.JavaMethodConverter; import com.thoughtworks.xstream.converters.extended.LocaleConverter; import com.thoughtworks.xstream.converters.extended.LookAndFeelConverter; import com.thoughtworks.xstream.converters.extended.SqlDateConverter; import com.thoughtworks.xstream.converters.extended.SqlTimeConverter; import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter; import com.thoughtworks.xstream.converters.extended.TextAttributeConverter; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.ClassLoaderReference; import com.thoughtworks.xstream.core.DefaultConverterLookup; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.MapBackedDataHolder; import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy; import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy; import com.thoughtworks.xstream.core.TreeMarshallingStrategy; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.core.util.SelfStreamingInstanceChecker; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.StatefulWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.AnnotationConfiguration; import com.thoughtworks.xstream.mapper.ArrayMapper; import com.thoughtworks.xstream.mapper.AttributeAliasingMapper; import com.thoughtworks.xstream.mapper.AttributeMapper; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.ClassAliasingMapper; import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper; import com.thoughtworks.xstream.mapper.DefaultMapper; import com.thoughtworks.xstream.mapper.DynamicProxyMapper; import com.thoughtworks.xstream.mapper.ElementIgnoringMapper; import com.thoughtworks.xstream.mapper.FieldAliasingMapper; import com.thoughtworks.xstream.mapper.ImmutableTypesMapper; import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper; import com.thoughtworks.xstream.mapper.LocalConversionMapper; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.mapper.OuterClassMapper; import com.thoughtworks.xstream.mapper.PackageAliasingMapper; import com.thoughtworks.xstream.mapper.SecurityMapper; import com.thoughtworks.xstream.mapper.SystemAttributeAliasingMapper; import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper; import com.thoughtworks.xstream.security.AnyTypePermission; import com.thoughtworks.xstream.security.ArrayTypePermission; import com.thoughtworks.xstream.security.ExplicitTypePermission; import com.thoughtworks.xstream.security.InterfaceTypePermission; import com.thoughtworks.xstream.security.NoPermission; import com.thoughtworks.xstream.security.NoTypePermission; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; import com.thoughtworks.xstream.security.RegExpTypePermission; import com.thoughtworks.xstream.security.TypeHierarchyPermission; import com.thoughtworks.xstream.security.TypePermission; import com.thoughtworks.xstream.security.WildcardTypePermission; /** * Simple facade to XStream library, a Java-XML serialization tool. * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre> * * </blockquote> * <hr> * <h3>Aliasing classes</h3> * <p> * To create shorter XML, you can specify aliases for classes using the <code>alias()</code> method. For example, you * can shorten all occurrences of element <code>&lt;com.blah.MyThing&gt;</code> to <code>&lt;my-thing&gt;</code> by * registering an alias for the class. * <p> * <hr> * <blockquote> * * <pre> * xstream.alias(&quot;my-thing&quot;, MyThing.class); * </pre> * * </blockquote> * <hr> * <h3>Converters</h3> * <p> * XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each of which acts as a * strategy for converting a particular type of class to XML and back again. Out of the box, XStream contains converters * for most basic types (String, Date, int, boolean, etc) and collections (Map, List, Set, Properties, etc). For other * objects reflection is used to serialize each field recursively. * </p> * <p> * Extra converters can be registered using the <code>registerConverter()</code> method. Some non-standard converters * are supplied in the {@link com.thoughtworks.xstream.converters.extended} package and you can create your own by * implementing the {@link com.thoughtworks.xstream.converters.Converter} interface. * </p> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre> * * </blockquote> * <hr> * <p> * The converters can be registered with an explicit priority. By default they are registered with * XStream.PRIORITY_NORMAL. Converters of same priority will be used in the reverse sequence they have been registered. * The default converter, i.e. the converter which will be used if no other registered converter is suitable, can be * registered with priority XStream.PRIORITY_VERY_LOW. XStream uses by default the * {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the fallback converter. * </p> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new CustomDefaultConverter(), XStream.PRIORITY_VERY_LOW); * </pre> * * </blockquote> * <hr> * <h3>Object graphs</h3> * <p> * XStream has support for object graphs; a deserialized object graph will keep references intact, including circular * references. * </p> * <p> * XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using * <code>setMode()</code>: * </p> * <table border='1'> * <caption></caption> * <tr> * <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML with the least * clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES);</code></td> * <td>Uses XPath relative references to signify duplicate references. The XPath expression ensures that a single node * only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate references. The XPath expression ensures that a single node * only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this * is easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object structure like a tree. Duplicate references are treated * as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than * the other two modes.</td> * </tr> * </table> * <h3>Thread safety</h3> * <p> * The XStream instance is thread-safe. That is, once the XStream instance has been created and configured, it may be * shared across multiple threads allowing objects to be serialized/deserialized concurrently. <em>Note, that this only * applies if annotations are not auto-detected on-the-fly.</em> * </p> * <h3>Implicit collections</h3> * <p> * To avoid the need for special tags for collections, you can define implicit collections using one of the * <code>addImplicitCollection</code> methods. * </p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @author Guilherme Silveira */ public class XStream { // CAUTION: The sequence of the fields is intentional for an optimal XML output of a // self-serialization! private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private ClassLoaderReference classLoaderReference; private MarshallingStrategy marshallingStrategy; private ConverterLookup converterLookup; private ConverterRegistry converterRegistry; private Mapper mapper; private PackageAliasingMapper packageAliasingMapper; private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private ElementIgnoringMapper elementIgnoringMapper; private AttributeAliasingMapper attributeAliasingMapper; private SystemAttributeAliasingMapper systemAttributeAliasingMapper; private AttributeMapper attributeMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private LocalConversionMapper localConversionMapper; private SecurityMapper securityMapper; private AnnotationConfiguration annotationConfiguration; private transient boolean securityInitialized; private transient boolean securityWarningGiven; public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_RELATIVE_REFERENCES = 1003; public static final int XPATH_ABSOLUTE_REFERENCES = 1004; public static final int SINGLE_NODE_XPATH_RELATIVE_REFERENCES = 1005; public static final int SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES = 1006; public static final int PRIORITY_VERY_HIGH = 10000; public static final int PRIORITY_NORMAL = 0; public static final int PRIORITY_LOW = -10; public static final int PRIORITY_VERY_LOW = -20; private static final String ANNOTATION_MAPPER_TYPE = "com.thoughtworks.xstream.mapper.AnnotationMapper"; private static final Pattern IGNORE_ALL = Pattern.compile(".*"); private static final Pattern LAZY_ITERATORS = Pattern.compile(".*\\$LazyIterator"); private static final Pattern JAVAX_CRYPTO = Pattern.compile("javax\\.crypto\\..*"); /** * Constructs a default XStream. * <p> * The instance will use the {@link XppDriver} as default and tries to determine the best match for the * {@link ReflectionProvider} on its own. * </p> * * @throws InitializationException in case of an initialization problem */ public XStream() { this(null, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link ReflectionProvider}. * <p> * The instance will use the {@link XppDriver} as default. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching reflection provider * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}. * <p> * The instance will tries to determine the best match for the {@link ReflectionProvider} on its own. * </p> * * @param hierarchicalStreamDriver the driver instance * @throws InitializationException in case of an initialization problem */ public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param hierarchicalStreamDriver the driver instance * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and a prepared * {@link Mapper} chain. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param driver the driver instance * @throws InitializationException in case of an initialization problem * @deprecated As of 1.3, use {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoader, Mapper)} * instead */ public XStream(ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { this(reflectionProvider, driver, new CompositeClassLoader(), mapper); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and a * {@link ClassLoaderReference}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference) { this(reflectionProvider, driver, classLoaderReference, null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and the * {@link ClassLoader} to use. * * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference)} */ public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { this(reflectionProvider, driver, classLoader, null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain and the {@link ClassLoader} to use. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoader the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use * {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference, Mapper)} */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, new DefaultConverterLookup()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain and the {@link ClassLoaderReference}. * <p> * The {@link ClassLoaderReference} should also be used for the {@link Mapper} chain. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper) { this(reflectionProvider, driver, classLoaderReference, mapper, new DefaultConverterLookup()); } private XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoader, Mapper mapper, final DefaultConverterLookup defaultConverterLookup) { this(reflectionProvider, driver, classLoader, mapper, new ConverterLookup() { public Converter lookupConverterForType(Class type) { return defaultConverterLookup.lookupConverterForType(type); } }, new ConverterRegistry() { public void registerConverter(Converter converter, int priority) { defaultConverterLookup.registerConverter(converter, priority); } }); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain, the {@link ClassLoaderReference} and an own {@link ConverterLookup} and * {@link ConverterRegistry}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoader the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param converterLookup the instance that is used to lookup the converters * @param converterRegistry an instance to manage the converter instances * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use * {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference, Mapper, ConverterLookup, ConverterRegistry)} */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, converterLookup, converterRegistry); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain, the {@link ClassLoaderReference} and an own {@link ConverterLookup} and * {@link ConverterRegistry}. * <p> * The ClassLoaderReference should also be used for the Mapper chain. The ConverterLookup should access the * ConverterRegistry if you intent to register {@link Converter} instances with XStream facade or you are using * annotations. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param converterLookup the instance that is used to lookup the converters * @param converterRegistry an instance to manage the converter instances or <em>null</em> to prevent any further * registry (including annotations) * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { if (reflectionProvider == null) { reflectionProvider = JVM.newReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = classLoaderReference; this.converterLookup = converterLookup; this.converterRegistry = converterRegistry; this.mapper = mapper == null ? buildMapper() : mapper; setupMappers(); setupSecurity(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if (useXStream11XmlFriendlyMapper()) { mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new DynamicProxyMapper(mapper); mapper = new PackageAliasingMapper(mapper); mapper = new ClassAliasingMapper(mapper); mapper = new ElementIgnoringMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new SystemAttributeAliasingMapper(mapper); mapper = new ImplicitCollectionMapper(mapper, reflectionProvider); mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider); if (JVM.isVersion(5)) { mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.EnumMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new LocalConversionMapper(mapper); mapper = new ImmutableTypesMapper(mapper); if (JVM.isVersion(8)) { mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.LambdaMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new SecurityMapper(mapper); if (JVM.isVersion(5)) { mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{ Mapper.class, ConverterRegistry.class, ConverterLookup.class, ClassLoaderReference.class, ReflectionProvider.class}, new Object[]{ mapper, converterRegistry, converterLookup, classLoaderReference, reflectionProvider}); } mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } private Mapper buildMapperDynamically(String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate mapper : " + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate mapper : " + className, e); } } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } /** * @deprecated As of 1.4.8 */ protected boolean useXStream11XmlFriendlyMapper() { return false; } private void setupMappers() { packageAliasingMapper = (PackageAliasingMapper)this.mapper.lookupMapperOfType(PackageAliasingMapper.class); classAliasingMapper = (ClassAliasingMapper)this.mapper.lookupMapperOfType(ClassAliasingMapper.class); elementIgnoringMapper = (ElementIgnoringMapper)this.mapper.lookupMapperOfType(ElementIgnoringMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper.lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper .lookupMapperOfType(SystemAttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper.lookupMapperOfType(ImmutableTypesMapper.class); localConversionMapper = (LocalConversionMapper)this.mapper.lookupMapperOfType(LocalConversionMapper.class); securityMapper = (SecurityMapper)this.mapper.lookupMapperOfType(SecurityMapper.class); annotationConfiguration = (AnnotationConfiguration)this.mapper .lookupMapperOfType(AnnotationConfiguration.class); } protected void setupSecurity() { if (securityMapper == null) { return; } addPermission(AnyTypePermission.ANY); denyTypes(new String[]{"java.beans.EventHandler"}); denyTypesByRegExp(new Pattern[]{LAZY_ITERATORS, JAVAX_CRYPTO}); allowTypeHierarchy(Exception.class); securityInitialized = false; } /** * Setup the security framework of a XStream instance. * <p> * This method is a pure helper method for XStream 1.4.x. It initializes an XStream instance with a white list of * well-known and simply types of the Java runtime as it is done in XStream 1.5.x by default. This method will do * therefore nothing in XStream 1.5. * </p> * * @param xstream * @since 1.4.10 */ public static void setupDefaultSecurity(final XStream xstream) { if (!xstream.securityInitialized) { xstream.addPermission(NoTypePermission.NONE); xstream.addPermission(NullPermission.NULL); xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); xstream.addPermission(ArrayTypePermission.ARRAYS); xstream.addPermission(InterfaceTypePermission.INTERFACES); xstream.allowTypeHierarchy(Calendar.class); xstream.allowTypeHierarchy(Collection.class); xstream.allowTypeHierarchy(Map.class); xstream.allowTypeHierarchy(Map.Entry.class); xstream.allowTypeHierarchy(Member.class); xstream.allowTypeHierarchy(Number.class); xstream.allowTypeHierarchy(Throwable.class); xstream.allowTypeHierarchy(TimeZone.class); Class type = JVM.loadClassForName("java.lang.Enum"); if (type != null) { xstream.allowTypeHierarchy(type); } type = JVM.loadClassForName("java.nio.file.Path"); if (type != null) { xstream.allowTypeHierarchy(type); } final Set types = new HashSet(); types.add(BitSet.class); types.add(Charset.class); types.add(Class.class); types.add(Currency.class); types.add(Date.class); types.add(DecimalFormatSymbols.class); types.add(File.class); types.add(Locale.class); types.add(Object.class); types.add(Pattern.class); types.add(StackTraceElement.class); types.add(String.class); types.add(StringBuffer.class); types.add(JVM.loadClassForName("java.lang.StringBuilder")); types.add(URL.class); types.add(URI.class); types.add(JVM.loadClassForName("java.util.UUID")); if (JVM.isSQLAvailable()) { types.add(JVM.loadClassForName("java.sql.Timestamp")); types.add(JVM.loadClassForName("java.sql.Time")); types.add(JVM.loadClassForName("java.sql.Date")); } if (JVM.isVersion(8)) { xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.Clock")); types.add(JVM.loadClassForName("java.time.Duration")); types.add(JVM.loadClassForName("java.time.Instant")); types.add(JVM.loadClassForName("java.time.LocalDate")); types.add(JVM.loadClassForName("java.time.LocalDateTime")); types.add(JVM.loadClassForName("java.time.LocalTime")); types.add(JVM.loadClassForName("java.time.MonthDay")); types.add(JVM.loadClassForName("java.time.OffsetDateTime")); types.add(JVM.loadClassForName("java.time.OffsetTime")); types.add(JVM.loadClassForName("java.time.Period")); types.add(JVM.loadClassForName("java.time.Ser")); types.add(JVM.loadClassForName("java.time.Year")); types.add(JVM.loadClassForName("java.time.YearMonth")); types.add(JVM.loadClassForName("java.time.ZonedDateTime")); xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.ZoneId")); types.add(JVM.loadClassForName("java.time.chrono.HijrahDate")); types.add(JVM.loadClassForName("java.time.chrono.JapaneseDate")); types.add(JVM.loadClassForName("java.time.chrono.JapaneseEra")); types.add(JVM.loadClassForName("java.time.chrono.MinguoDate")); types.add(JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate")); types.add(JVM.loadClassForName("java.time.chrono.Ser")); xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.chrono.Chronology")); types.add(JVM.loadClassForName("java.time.temporal.ValueRange")); types.add(JVM.loadClassForName("java.time.temporal.WeekFields")); } types.remove(null); final Iterator iter = types.iterator(); final Class[] classes = new Class[types.size()]; for (int i = 0; i < classes.length; ++i) { classes[i] = (Class)iter.next(); } xstream.allowTypes(classes); } else { throw new IllegalArgumentException("Security framework of XStream instance already initialized"); } } protected void setupAliases() { if (classAliasingMapper == null) { return; } alias("null", Mapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("field", Field.class); alias("date", Date.class); alias("uri", URI.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("sorted-set", SortedSet.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); alias("empty-list", Collections.EMPTY_LIST.getClass()); alias("empty-map", Collections.EMPTY_MAP.getClass()); alias("empty-set", Collections.EMPTY_SET.getClass()); alias("singleton-list", Collections.singletonList(this).getClass()); alias("singleton-map", Collections.singletonMap(this, null).getClass()); alias("singleton-set", Collections.singleton(this).getClass()); if (JVM.isAWTAvailable()) { // Instantiating these two classes starts the AWT system, which is undesirable. // Calling loadClass ensures a reference to the class is found but they are not // instantiated. alias("awt-color", JVM.loadClassForName("java.awt.Color", false)); alias("awt-font", JVM.loadClassForName("java.awt.Font", false)); alias("awt-text-attribute", JVM.loadClassForName("java.awt.font.TextAttribute")); } Class type = JVM.loadClassForName("javax.activation.ActivationDataFlavor"); if (type != null) { alias("activation-data-flavor", type); } if (JVM.isSQLAvailable()) { alias("sql-timestamp", JVM.loadClassForName("java.sql.Timestamp")); alias("sql-time", JVM.loadClassForName("java.sql.Time")); alias("sql-date", JVM.loadClassForName("java.sql.Date")); } alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); if (JVM.isVersion(4)) { aliasDynamically("auth-subject", "javax.security.auth.Subject"); alias("linked-hash-map", JVM.loadClassForName("java.util.LinkedHashMap")); alias("linked-hash-set", JVM.loadClassForName("java.util.LinkedHashSet")); alias("trace", JVM.loadClassForName("java.lang.StackTraceElement")); alias("currency", JVM.loadClassForName("java.util.Currency")); aliasType("charset", JVM.loadClassForName("java.nio.charset.Charset")); } if (JVM.isVersion(5)) { aliasDynamically("xml-duration", "javax.xml.datatype.Duration"); alias("concurrent-hash-map", JVM.loadClassForName("java.util.concurrent.ConcurrentHashMap")); alias("enum-set", JVM.loadClassForName("java.util.EnumSet")); alias("enum-map", JVM.loadClassForName("java.util.EnumMap")); alias("string-builder", JVM.loadClassForName("java.lang.StringBuilder")); alias("uuid", JVM.loadClassForName("java.util.UUID")); } if (JVM.isVersion(7)) { aliasType("path", JVM.loadClassForName("java.nio.file.Path")); } if (JVM.isVersion(8)) { alias("fixed-clock", JVM.loadClassForName("java.time.Clock$FixedClock")); alias("offset-clock", JVM.loadClassForName("java.time.Clock$OffsetClock")); alias("system-clock", JVM.loadClassForName("java.time.Clock$SystemClock")); alias("tick-clock", JVM.loadClassForName("java.time.Clock$TickClock")); alias("day-of-week", JVM.loadClassForName("java.time.DayOfWeek")); alias("duration", JVM.loadClassForName("java.time.Duration")); alias("instant", JVM.loadClassForName("java.time.Instant")); alias("local-date", JVM.loadClassForName("java.time.LocalDate")); alias("local-date-time", JVM.loadClassForName("java.time.LocalDateTime")); alias("local-time", JVM.loadClassForName("java.time.LocalTime")); alias("month", JVM.loadClassForName("java.time.Month")); alias("month-day", JVM.loadClassForName("java.time.MonthDay")); alias("offset-date-time", JVM.loadClassForName("java.time.OffsetDateTime")); alias("offset-time", JVM.loadClassForName("java.time.OffsetTime")); alias("period", JVM.loadClassForName("java.time.Period")); alias("year", JVM.loadClassForName("java.time.Year")); alias("year-month", JVM.loadClassForName("java.time.YearMonth")); alias("zoned-date-time", JVM.loadClassForName("java.time.ZonedDateTime")); aliasType("zone-id", JVM.loadClassForName("java.time.ZoneId")); aliasType("chronology", JVM.loadClassForName("java.time.chrono.Chronology")); alias("hijrah-date", JVM.loadClassForName("java.time.chrono.HijrahDate")); alias("hijrah-era", JVM.loadClassForName("java.time.chrono.HijrahEra")); alias("japanese-date", JVM.loadClassForName("java.time.chrono.JapaneseDate")); alias("japanese-era", JVM.loadClassForName("java.time.chrono.JapaneseEra")); alias("minguo-date", JVM.loadClassForName("java.time.chrono.MinguoDate")); alias("minguo-era", JVM.loadClassForName("java.time.chrono.MinguoEra")); alias("thai-buddhist-date", JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate")); alias("thai-buddhist-era", JVM.loadClassForName("java.time.chrono.ThaiBuddhistEra")); alias("chrono-field", JVM.loadClassForName("java.time.temporal.ChronoField")); alias("chrono-unit", JVM.loadClassForName("java.time.temporal.ChronoUnit")); alias("iso-field", JVM.loadClassForName("java.time.temporal.IsoFields$Field")); alias("iso-unit", JVM.loadClassForName("java.time.temporal.IsoFields$Unit")); alias("julian-field", JVM.loadClassForName("java.time.temporal.JulianFields$Field")); alias("temporal-value-range", JVM.loadClassForName("java.time.temporal.ValueRange")); alias("week-fields", JVM.loadClassForName("java.time.temporal.WeekFields")); } if (JVM.loadClassForName("java.lang.invoke.SerializedLambda") != null) { aliasDynamically("serialized-lambda", "java.lang.invoke.SerializedLambda"); } } private void aliasDynamically(String alias, String className) { Class type = JVM.loadClassForName(className); if (type != null) { alias(alias, type); } } protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(TreeSet.class, SortedSet.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { registerConverter(new ReflectionConverter(mapper, reflectionProvider), PRIORITY_VERY_LOW); registerConverter(new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URIConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonCollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter((Converter)new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if (JVM.isSQLAvailable()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL); if (JVM.isAWTAvailable()) { registerConverter(new FontConverter(mapper), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } if (JVM.isSwingAvailable()) { registerConverter(new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.isVersion(4)) { // late bound converters - allows XStream to be compiled on earlier JDKs registerConverterDynamically("com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[]{ConverterLookup.class}, new Object[]{converterLookup}); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(5)) { // late bound converters - allows XStream to be compiled on earlier JDKs if (JVM.loadClassForName("javax.xml.datatype.Duration") != null) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.DurationConverter", PRIORITY_NORMAL, null, null); } registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.basic.StringBuilderConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.basic.UUIDConverter", PRIORITY_NORMAL, null, null); } if (JVM.loadClassForName("javax.activation.ActivationDataFlavor") != null) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.ActivationDataFlavorConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(7)) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.PathConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(8)) { registerConverterDynamically("com.thoughtworks.xstream.converters.time.ChronologyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.DurationConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.HijrahDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseEraConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.InstantConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.MinguoDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.MonthDayConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.PeriodConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.SystemClockConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ValueRangeConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.WeekFieldsConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearMonthConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZoneIdConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.reflection.LambdaConverter", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class, ClassLoaderReference.class}, new Object[]{mapper, reflectionProvider, classLoaderReference}); } registerConverter(new SelfStreamingInstanceChecker(converterLookup, this), PRIORITY_NORMAL); } private void registerConverterDynamically(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate converter : " + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate converter : " + className, e); } } protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class, false); addImmutableType(Boolean.class, false); addImmutableType(byte.class, false); addImmutableType(Byte.class, false); addImmutableType(char.class, false); addImmutableType(Character.class, false); addImmutableType(double.class, false); addImmutableType(Double.class, false); addImmutableType(float.class, false); addImmutableType(Float.class, false); addImmutableType(int.class, false); addImmutableType(Integer.class, false); addImmutableType(long.class, false); addImmutableType(Long.class, false); addImmutableType(short.class, false); addImmutableType(Short.class, false); // additional types addImmutableType(Mapper.Null.class, false); addImmutableType(BigDecimal.class, false); addImmutableType(BigInteger.class, false); addImmutableType(String.class, false); addImmutableType(URL.class, false); addImmutableType(File.class, false); addImmutableType(Class.class, false); if (JVM.isVersion(7)) { Class type = JVM.loadClassForName("java.nio.file.Paths"); if (type != null) { Method methodGet; try { methodGet = type.getDeclaredMethod("get", new Class[]{String.class, String[].class}); if (methodGet != null) { Object path = methodGet.invoke(null, new Object[]{".", new String[0]}); if (path != null) { addImmutableType(path.getClass(), false); } } } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } if (JVM.isAWTAvailable()) { addImmutableTypeDynamically("java.awt.font.TextAttribute", false); } if (JVM.isVersion(4)) { // late bound types - allows XStream to be compiled on earlier JDKs addImmutableTypeDynamically("java.nio.charset.Charset", true); addImmutableTypeDynamically("java.util.Currency", true); } if (JVM.isVersion(5)) { addImmutableTypeDynamically("java.util.UUID", true); } addImmutableType(URI.class, true); addImmutableType(Collections.EMPTY_LIST.getClass(), true); addImmutableType(Collections.EMPTY_SET.getClass(), true); addImmutableType(Collections.EMPTY_MAP.getClass(), true); if (JVM.isVersion(8)) { addImmutableTypeDynamically("java.time.Duration", false); addImmutableTypeDynamically("java.time.Instant", false); addImmutableTypeDynamically("java.time.LocalDate", false); addImmutableTypeDynamically("java.time.LocalDateTime", false); addImmutableTypeDynamically("java.time.LocalTime", false); addImmutableTypeDynamically("java.time.MonthDay", false); addImmutableTypeDynamically("java.time.OffsetDateTime", false); addImmutableTypeDynamically("java.time.OffsetTime", false); addImmutableTypeDynamically("java.time.Period", false); addImmutableTypeDynamically("java.time.Year", false); addImmutableTypeDynamically("java.time.YearMonth", false); addImmutableTypeDynamically("java.time.ZonedDateTime", false); addImmutableTypeDynamically("java.time.ZoneId", false); addImmutableTypeDynamically("java.time.ZoneOffset", false); addImmutableTypeDynamically("java.time.ZoneRegion", false); addImmutableTypeDynamically("java.time.chrono.HijrahChronology", false); addImmutableTypeDynamically("java.time.chrono.HijrahDate", false); addImmutableTypeDynamically("java.time.chrono.IsoChronology", false); addImmutableTypeDynamically("java.time.chrono.JapaneseChronology", false); addImmutableTypeDynamically("java.time.chrono.JapaneseDate", false); addImmutableTypeDynamically("java.time.chrono.JapaneseEra", false); addImmutableTypeDynamically("java.time.chrono.MinguoChronology", false); addImmutableTypeDynamically("java.time.chrono.MinguoDate", false); addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistChronology", false); addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistDate", false); addImmutableTypeDynamically("java.time.temporal.IsoFields$Field", false); addImmutableTypeDynamically("java.time.temporal.IsoFields$Unit", false); addImmutableTypeDynamically("java.time.temporal.JulianFields$Field", false); } } private void addImmutableTypeDynamically(String className, boolean isReferenceable) { Class type = JVM.loadClassForName(className); if (type != null) { addImmutableType(type, isReferenceable); } } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. * * @throws XStreamException if the object cannot be serialized */ public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. The Writer will be flushed afterwards and in case * of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize an object to the given OutputStream as pretty-printed XML. The OutputStream will be flushed afterwards * and in case of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize and object to a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, * XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } /** * Deserialize an object from an XML String. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader reader) { return unmarshal(hierarchicalStreamDriver.createReader(reader), null); } /** * Deserialize an object from an XML InputStream. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } /** * Deserialize an object from a URL. Depending on the parser implementation, some might take the file path as * SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(URL url) { return fromXML(url, null); } /** * Deserialize an object from a file. Depending on the parser implementation, some might take the file path as * SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(File file) { return fromXML(file, null); } /** * Deserialize an object from an XML String, populating the fields of the given root object instead of instantiating * a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into * the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, populating the fields of the given root object instead of instantiating * a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into * the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a URL, populating the fields of the given root object instead of instantiating a new * one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw * memory area of the existing object. Use with care! Depending on the parser implementation, some might take the * file path as SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(URL url, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(url), root); } /** * Deserialize an object from a file, populating the fields of the given root object instead of instantiating a new * one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw * memory area of the existing object. Use with care! Depending on the parser implementation, some might take the * file path as SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(File file, Object root) { HierarchicalStreamReader reader = hierarchicalStreamDriver.createReader(file); try { return unmarshal(reader, root); } finally { reader.close(); } } /** * Deserialize an object from an XML InputStream, populating the fields of the given root object instead of * instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write * directly into the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(input), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), populating the fields of the given root * object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter * XStream will write directly into the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed to XStream creating a new * instance. Note, that this is a special use case! With the ReflectionConverter XStream will write * directly into the raw memory area of the existing object. Use with care! * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, * XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { try { if (!securityInitialized && !securityWarningGiven) { securityWarningGiven = true; System.err .println( "Security framework of XStream not explicitly initialized, using predefined black list on your own risk."); } return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper); } catch (ConversionException e) { Package pkg = getClass().getPackage(); String version = pkg != null ? pkg.getImplementationVersion() : null; e.add("version", version != null ? version : "not available"); throw e; } } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addClassAlias(name, type); } /** * Alias a type to a shorter name to be used in XML elements. Any class that is assignable to this type will be * aliased to the same name. * * @param name Short name * @param type Type to be aliased * @since 1.2 * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addTypeAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is * available */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } /** * Alias a package to a shorter name to be used in XML elements. * * @param name Short name * @param pkgName package to be aliased * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link PackageAliasingMapper} is * available * @since 1.3.1 */ public void aliasPackage(String name, String pkgName) { if (packageAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + PackageAliasingMapper.class.getName() + " available"); } packageAliasingMapper.addPackageAlias(name, pkgName); } /** * Create an alias for a field name. * * @param alias the alias itself * @param definedIn the type that declares the field * @param fieldName the name of the field * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void aliasField(String alias, Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName); } /** * Create an alias for an attribute * * @param alias the alias itself * @param attributeName the name of the attribute * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(attributeName, alias); } /** * Create an alias for a system attribute. XStream will not write a system attribute if its alias is set to * <code>null</code>. However, this is not reversible, i.e. deserialization of the result is likely to fail * afterwards and will not produce an object equal to the originally written one. * * @param alias the alias itself (may be <code>null</code>) * @param systemAttributeName the name of the system attribute * @throws InitializationException if no {@link SystemAttributeAliasingMapper} is available * @since 1.3.1 */ public void aliasSystemAttribute(String alias, String systemAttributeName) { if (systemAttributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + SystemAttributeAliasingMapper.class.getName() + " available"); } systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias); } /** * Create an alias for an attribute. * * @param definedIn the type where the attribute is defined * @param attributeName the name of the attribute * @param alias the alias itself * @throws InitializationException if no {@link AttributeAliasingMapper} is available * @since 1.2.2 */ public void aliasAttribute(Class definedIn, String attributeName, String alias) { aliasField(alias, definedIn, attributeName); useAttributeFor(definedIn, attributeName); } /** * Use an attribute for a field or a specific type. * * @param fieldName the name of the field * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(fieldName, type); } /** * Use an attribute for a field declared in a specific type. * * @param fieldName the name of the field * @param definedIn the Class containing such field * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2.2 */ public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(definedIn, fieldName); } /** * Use an attribute for an arbitrary type. * * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(type); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters an instance of this * type, it will use the default implementation instead. For example, java.util.ArrayList is the default * implementation of java.util.List. * * @param defaultImplementation * @param ofType * @throws InitializationException if no {@link DefaultImplementationsMapper} is available */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + DefaultImplementationsMapper.class.getName() + " available"); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } /** * Add immutable types. The value of the instances of these types will always be written into the stream even if * they appear multiple times. However, references are still supported at deserialization time. * * @throws InitializationException if no {@link ImmutableTypesMapper} is available * @deprecated As of 1.4.9 use {@link #addImmutableType(Class, boolean)} */ public void addImmutableType(Class type) { addImmutableType(type, true); } /** * Add immutable types. The value of the instances of these types will always be written into the stream even if * they appear multiple times. * <p> * Note, while a reference-keeping marshaller will not write references for immutable types into the stream, a * reference-keeping unmarshaller can still support such references in the stream for compatibility reasons at the * expense of memory consumption. Therefore declare these types only as referenceable if your already persisted * streams do contain such references. Otherwise you may waste a lot of memory during deserialization. * </p> * * @param isReferenceable <code>true</code> if support at deserialization time is required for compatibility at the * cost of a higher memory footprint, <code>false</code> otherwise * @throws InitializationException if no {@link ImmutableTypesMapper} is available * @since 1.4.9 */ public void addImmutableType(final Class type, final boolean isReferenceable) { if (immutableTypesMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImmutableTypesMapper.class.getName() + " available"); } immutableTypesMapper.addImmutableType(type, isReferenceable); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(converter, priority); } } public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(SingleValueConverter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(new SingleValueConverterWrapper(converter), priority); } } /** * Register a local {@link Converter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) { if (localConversionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + LocalConversionMapper.class.getName() + " available"); } localConversionMapper.registerLocalConverter(definedIn, fieldName, converter); } /** * Register a local {@link SingleValueConverter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) { registerLocalConverter(definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter)); } /** * Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}. * * @return the mapper * @since 1.2 */ public Mapper getMapper() { return mapper; } /** * Retrieve the {@link ReflectionProvider} in use. * * @return the mapper * @since 1.2.1 */ public ReflectionProvider getReflectionProvider() { return reflectionProvider; } public ConverterLookup getConverterLookup() { return converterLookup; } /** * Change mode for dealing with duplicate references. Valid values are <code>XPATH_ABSOLUTE_REFERENCES</code>, * <code>XPATH_RELATIVE_REFERENCES</code>, <code>XStream.ID_REFERENCES</code> and * <code>XStream.NO_REFERENCES</code>. * * @throws IllegalArgumentException if the mode is not one of the declared types * @see #XPATH_ABSOLUTE_REFERENCES * @see #XPATH_RELATIVE_REFERENCES * @see #ID_REFERENCES * @see #NO_REFERENCES */ public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; case SINGLE_NODE_XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(ReferenceByXPathMarshallingStrategy.RELATIVE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; case SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(ReferenceByXPathMarshallingStrategy.ABSOLUTE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * Adds a default implicit collection which is used for any unmapped XML tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. */ public void addImplicitCollection(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName, null, null); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. * @param itemType type of the items to be part of this collection * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { addImplicitMap(ownerType, fieldName, itemFieldName, itemType, null); } /** * Adds an implicit array. * * @param ownerType class owning the implicit array * @param fieldName name of the array field * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } /** * Adds an implicit array which is used for all items of the given itemType when the array type matches. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemType type of the items to be part of this array * @throws InitializationException if no {@link ImplicitCollectionMapper} is available or the array type does not * match the itemType * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, itemType); } /** * Adds an implicit array which is used for all items of the given element name defined by itemName. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemName alias name of the items * @throws InitializationException if no {@link ImplicitCollectionMapper} is available * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName, String itemName) { addImplicitCollection(ownerType, fieldName, itemName, null); } /** * Adds an implicit map. * * @param ownerType class owning the implicit map * @param fieldName name of the field in the ownerType. This field must be a concrete map type or matching the * default implementation type of the map type. * @param itemType type of the items to be part of this map as value * @param keyFieldName the name of the field of the itemType that is used for the key in the map * @since 1.4 */ public void addImplicitMap(Class ownerType, String fieldName, Class itemType, String keyFieldName) { addImplicitMap(ownerType, fieldName, null, itemType, keyFieldName); } /** * Adds an implicit map. * * @param ownerType class owning the implicit map * @param fieldName name of the field in the ownerType. This field must be a concrete map type or matching the * default implementation type of the map type. * @param itemName alias name of the items * @param itemType type of the items to be part of this map as value * @param keyFieldName the name of the field of the itemType that is used for the key in the map * @since 1.4 */ public void addImplicitMap(Class ownerType, String fieldName, String itemName, Class itemType, String keyFieldName) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, itemName, itemType, keyFieldName); } /** * Create a DataHolder that can be used to pass data to the converters. The DataHolder is provided with a call to * {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)}, * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}, * {@link #createObjectInputStream(HierarchicalStreamReader, DataHolder)} or * {@link #createObjectOutputStream(HierarchicalStreamWriter, String, DataHolder)}. * * @return a new {@link DataHolder} */ public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * Because an ObjectOutputStream can contain multiple items and XML only allows a single root node, the stream must * be written inside an enclosing node. * </p> * <p> * It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be incomplete. * </p> * <h3>Example</h3> * * <pre> * ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, &quot;things&quot;); * out.writeInt(123); * out.writeObject(&quot;Hello&quot;); * out.writeObject(someObject) * out.close(); * </pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName) throws IOException { return createObjectOutputStream(writer, rootNodeName, null); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.4.10 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName, final DataHolder dataHolder) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(final Object object) { marshal(object, statefulWriter, dataHolder); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from an InputStream using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.3 */ public ObjectInputStream createObjectInputStream(InputStream in) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(in)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * <p> * It is necessary to call ObjectInputStream.close() when done, otherwise the stream might keep system resources. * </p> * <h3>Example</h3> * * <pre> * ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject(); * </pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return createObjectInputStream(reader, null); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.4.10 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); final Object result = unmarshal(reader, null, dataHolder); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }, classLoaderReference); } /** * Change the ClassLoader XStream uses to load classes. Creating an XStream instance it will register for all kind * of classes and types of the current JDK, but not for any 3rd party type. To ensure that all other types are * loaded with your class loader, you should call this method as early as possible - or consider to provide the * class loader directly in the constructor. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Retrieve the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } /** * Retrieve the reference to this instance' ClassLoader. Use this reference for other XStream components (like * converters) to ensure that they will use a changed ClassLoader instance automatically. * * @return the reference * @since 1.4.5 */ public ClassLoaderReference getClassLoaderReference() { return classLoaderReference; } /** * Prevents a field from being serialized. To omit a field you must always provide the declaring type and not * necessarily the type that is converted. * * @since 1.1.3 * @throws InitializationException if no {@link ElementIgnoringMapper} is available */ public void omitField(Class definedIn, String fieldName) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ElementIgnoringMapper.class.getName() + " available"); } elementIgnoringMapper.omitField(definedIn, fieldName); } /** * Ignore all unknown elements. * * @since 1.4.5 */ public void ignoreUnknownElements() { ignoreUnknownElements(IGNORE_ALL); } /** * Add pattern for unknown element names to ignore. * * @param pattern the name pattern as regular expression * @since 1.4.5 */ public void ignoreUnknownElements(String pattern) { ignoreUnknownElements(Pattern.compile(pattern)); } /** * Add pattern for unknown element names to ignore. * * @param pattern the name pattern as regular expression * @since 1.4.5 */ public void ignoreUnknownElements(final Pattern pattern) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ElementIgnoringMapper.class.getName() + " available"); } elementIgnoringMapper.addElementsToIgnore(pattern); } /** * Process the annotations of the given types and configure the XStream. * * @param types the types with XStream annotations * @since 1.3 */ public void processAnnotations(final Class[] types) { if (annotationConfiguration == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ANNOTATION_MAPPER_TYPE + " available"); } annotationConfiguration.processAnnotations(types); } /** * Process the annotations of the given type and configure the XStream. A call of this method will automatically * turn the auto-detection mode for annotations off. * * @param type the type with XStream annotations * @since 1.3 */ public void processAnnotations(final Class type) { processAnnotations(new Class[]{type}); } /** * Set the auto-detection mode of the AnnotationMapper. Note that auto-detection implies that the XStream is * configured while it is processing the XML steams. This is a potential concurrency problem. Also is it technically * not possible to detect all class aliases at deserialization. You have been warned! * * @param mode <code>true</code> if annotations are auto-detected * @since 1.3 */ public void autodetectAnnotations(boolean mode) { if (annotationConfiguration != null) { annotationConfiguration.autodetectAnnotations(mode); } } /** * Add a new security permission. * <p> * Permissions are evaluated in the added sequence. An instance of {@link NoTypePermission} or * {@link AnyTypePermission} will implicitly wipe any existing permission. * </p> * * @param permission the permission to add * @since 1.4.7 */ public void addPermission(TypePermission permission) { if (securityMapper != null) { securityInitialized |= permission.equals(NoTypePermission.NONE) || permission.equals(AnyTypePermission.ANY); securityMapper.addPermission(permission); } } /** * Add security permission for explicit types by name. * * @param names the type names to allow * @since 1.4.7 */ public void allowTypes(String[] names) { addPermission(new ExplicitTypePermission(names)); } /** * Add security permission for explicit types. * * @param types the types to allow * @since 1.4.7 */ public void allowTypes(Class[] types) { addPermission(new ExplicitTypePermission(types)); } /** * Add security permission for a type hierarchy. * * @param type the base type to allow * @since 1.4.7 */ public void allowTypeHierarchy(Class type) { addPermission(new TypeHierarchyPermission(type)); } /** * Add security permission for types matching one of the specified regular expressions. * * @param regexps the regular expressions to allow type names * @since 1.4.7 */ public void allowTypesByRegExp(String[] regexps) { addPermission(new RegExpTypePermission(regexps)); } /** * Add security permission for types matching one of the specified regular expressions. * * @param regexps the regular expressions to allow type names * @since 1.4.7 */ public void allowTypesByRegExp(Pattern[] regexps) { addPermission(new RegExpTypePermission(regexps)); } /** * Add security permission for types matching one of the specified wildcard patterns. * <p> * Supported are patterns with path expressions using dot as separator: * </p> * <ul> * <li>?: one non-control character except separator, e.g. for 'java.net.Inet?Address'</li> * <li>*: arbitrary number of non-control characters except separator, e.g. for types in a package like * 'java.lang.*'</li> * <li>**: arbitrary number of non-control characters including separator, e.g. for types in a package and * subpackages like 'java.lang.**'</li> * </ul> * * @param patterns the patterns to allow type names * @since 1.4.7 */ public void allowTypesByWildcard(String[] patterns) { addPermission(new WildcardTypePermission(patterns)); } /** * Add security permission denying another one. * * @param permission the permission to deny * @since 1.4.7 */ public void denyPermission(TypePermission permission) { addPermission(new NoPermission(permission)); } /** * Add security permission forbidding explicit types by name. * * @param names the type names to forbid * @since 1.4.7 */ public void denyTypes(String[] names) { denyPermission(new ExplicitTypePermission(names)); } /** * Add security permission forbidding explicit types. * * @param types the types to forbid * @since 1.4.7 */ public void denyTypes(Class[] types) { denyPermission(new ExplicitTypePermission(types)); } /** * Add security permission forbidding a type hierarchy. * * @param type the base type to forbid * @since 1.4.7 */ public void denyTypeHierarchy(Class type) { denyPermission(new TypeHierarchyPermission(type)); } /** * Add security permission forbidding types matching one of the specified regular expressions. * * @param regexps the regular expressions to forbid type names * @since 1.4.7 */ public void denyTypesByRegExp(String[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } /** * Add security permission forbidding types matching one of the specified regular expressions. * * @param regexps the regular expressions to forbid type names * @since 1.4.7 */ public void denyTypesByRegExp(Pattern[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } /** * Add security permission forbidding types matching one of the specified wildcard patterns. * <p> * Supported are patterns with path expressions using dot as separator: * </p> * <ul> * <li>?: one non-control character except separator, e.g. for 'java.net.Inet?Address'</li> * <li>*: arbitrary number of non-control characters except separator, e.g. for types in a package like * 'java.lang.*'</li> * <li>**: arbitrary number of non-control characters including separator, e.g. for types in a package and * subpackages like 'java.lang.**'</li> * </ul> * * @param patterns the patterns to forbid names * @since 1.4.7 */ public void denyTypesByWildcard(String[] patterns) { denyPermission(new WildcardTypePermission(patterns)); } private Object readResolve() { securityWarningGiven = true; return this; } /** * @deprecated As of 1.3, use {@link com.thoughtworks.xstream.InitializationException} instead */ public static class InitializationException extends XStreamException { /** * @deprecated As of 1.3, use * {@link com.thoughtworks.xstream.InitializationException#InitializationException(String, Throwable)} * instead */ public InitializationException(String message, Throwable cause) { super(message, cause); } /** * @deprecated As of 1.3, use * {@link com.thoughtworks.xstream.InitializationException#InitializationException(String)} instead */ public InitializationException(String message) { super(message); } } }
./CrossVul/dataset_final_sorted/CWE-78/java/bad_4334_1
crossvul-java_data_bad_2537_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-78/java/bad_2537_1
crossvul-java_data_good_4334_2
/* * Copyright (C) 2013, 2014, 2017, 2018, 2020 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 23. December 2013 by Joerg Schaible */ package com.thoughtworks.acceptance; import java.beans.EventHandler; import java.util.Iterator; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.security.AnyTypePermission; import com.thoughtworks.xstream.security.ForbiddenClassException; /** * @author J&ouml;rg Schaible */ public class SecurityVulnerabilityTest extends AbstractAcceptanceTest { private final static StringBuffer BUFFER = new StringBuffer(); protected void setUp() throws Exception { super.setUp(); BUFFER.setLength(0); xstream.alias("runnable", Runnable.class); } protected void setupSecurity(XStream xstream) { } public void testCannotInjectEventHandler() { final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; try { xstream.fromXML(xml); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName()) > 0); } assertEquals(0, BUFFER.length()); } public void testCannotInjectEventHandlerWithUnconfiguredSecurityFramework() { xstream.alias("runnable", Runnable.class); final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; try { xstream.fromXML(xml); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName()) >= 0); } assertEquals(0, BUFFER.length()); } public void testExplicitlyConvertEventHandler() { final String xml = "" + "<string class='runnable-array'>\n" + " <dynamic-proxy>\n" + " <interface>java.lang.Runnable</interface>\n" + " <handler class='java.beans.EventHandler'>\n" + " <target class='com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec'/>\n" + " <action>exec</action>\n" + " </handler>\n" + " </dynamic-proxy>\n" + "</string>"; xstream.allowTypes(new Class[]{EventHandler.class}); final Runnable[] array = (Runnable[])xstream.fromXML(xml); assertEquals(0, BUFFER.length()); array[0].run(); assertEquals("Executed!", BUFFER.toString()); } public void testCannotInjectConvertImageIOContainsFilterWithUnconfiguredSecurityFramework() { if (JVM.isVersion(7)) { final String xml = "" + "<string class='javax.imageio.spi.FilterIterator'>\n" + " <iter class='java.util.ArrayList$Itr'>\n" + " <cursor>0</cursor>\n" + " <lastRet>1</lastRet>\n" + " <expectedModCount>1</expectedModCount>\n" + " <outer-class>\n" + " <com.thoughtworks.acceptance.SecurityVulnerabilityTest_-Exec/>\n" + " </outer-class>\n" + " </iter>\n" + " <filter class='javax.imageio.ImageIO$ContainsFilter'>\n" + " <method>\n" + " <class>com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec</class>\n" + " <name>exec</name>\n" + " <parameter-types/>\n" + " </method>\n" + " <name>exec</name>\n" + " </filter>\n" + " <next/>\n" + "</string>"; try { xstream.fromXML(xml); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf("javax.imageio.ImageIO$ContainsFilter") >= 0); } assertEquals(0, BUFFER.length()); } } public void testExplicitlyConvertImageIOContainsFilter() { if (JVM.isVersion(7)) { final String xml = "" + "<string class='javax.imageio.spi.FilterIterator'>\n" + " <iter class='java.util.ArrayList$Itr'>\n" + " <cursor>0</cursor>\n" + " <lastRet>1</lastRet>\n" + " <expectedModCount>1</expectedModCount>\n" + " <outer-class>\n" + " <com.thoughtworks.acceptance.SecurityVulnerabilityTest_-Exec/>\n" + " </outer-class>\n" + " </iter>\n" + " <filter class='javax.imageio.ImageIO$ContainsFilter'>\n" + " <method>\n" + " <class>com.thoughtworks.acceptance.SecurityVulnerabilityTest$Exec</class>\n" + " <name>exec</name>\n" + " <parameter-types/>\n" + " </method>\n" + " <name>exec</name>\n" + " </filter>\n" + " <next/>\n" + "</string>"; xstream.allowTypes(new String[]{"javax.imageio.ImageIO$ContainsFilter"}); final Iterator iterator = (Iterator)xstream.fromXML(xml); assertEquals(0, BUFFER.length()); iterator.next(); assertEquals("Executed!", BUFFER.toString()); } } public static class Exec { public void exec() { BUFFER.append("Executed!"); } } public void testInstanceOfVoid() { try { xstream.fromXML("<void/>"); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { assertEquals("void", e.get("construction-type")); } } public void testDeniedInstanceOfVoid() { xstream.addPermission(AnyTypePermission.ANY); // clear out defaults xstream.denyTypes(new Class[]{void.class, Void.class}); try { xstream.fromXML("<void/>"); fail("Thrown " + ForbiddenClassException.class.getName() + " expected"); } catch (final ForbiddenClassException e) { // OK } } public void testAllowedInstanceOfVoid() { xstream.allowTypes(new Class[]{void.class, Void.class}); try { xstream.fromXML("<void/>"); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { assertEquals("void", e.get("construction-type")); } } public static class LazyIterator {} public void testInstanceOfLazyIterator() { xstream.alias("lazy-iterator", LazyIterator.class); try { xstream.fromXML("<lazy-iterator/>"); fail("Thrown " + ForbiddenClassException.class.getName() + " expected"); } catch (final ForbiddenClassException e) { // OK } } }
./CrossVul/dataset_final_sorted/CWE-78/java/good_4334_2
crossvul-java_data_bad_2537_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-78/java/bad_2537_2
crossvul-java_data_good_4334_1
/* * Copyright (C) 2003, 2004, 2005, 2006 Joe Walnes. * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2020 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 26. September 2003 by Joe Walnes */ package com.thoughtworks.xstream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Pattern; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.ConverterRegistry; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.BigDecimalConverter; import com.thoughtworks.xstream.converters.basic.BigIntegerConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.ByteConverter; import com.thoughtworks.xstream.converters.basic.CharConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.basic.DoubleConverter; import com.thoughtworks.xstream.converters.basic.FloatConverter; import com.thoughtworks.xstream.converters.basic.IntConverter; import com.thoughtworks.xstream.converters.basic.LongConverter; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.basic.ShortConverter; import com.thoughtworks.xstream.converters.basic.StringBufferConverter; import com.thoughtworks.xstream.converters.basic.StringConverter; import com.thoughtworks.xstream.converters.basic.URIConverter; import com.thoughtworks.xstream.converters.basic.URLConverter; import com.thoughtworks.xstream.converters.collections.ArrayConverter; import com.thoughtworks.xstream.converters.collections.BitSetConverter; import com.thoughtworks.xstream.converters.collections.CharArrayConverter; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.converters.collections.SingletonCollectionConverter; import com.thoughtworks.xstream.converters.collections.SingletonMapConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.converters.collections.TreeSetConverter; import com.thoughtworks.xstream.converters.extended.ColorConverter; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.FileConverter; import com.thoughtworks.xstream.converters.extended.FontConverter; import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter; import com.thoughtworks.xstream.converters.extended.JavaClassConverter; import com.thoughtworks.xstream.converters.extended.JavaFieldConverter; import com.thoughtworks.xstream.converters.extended.JavaMethodConverter; import com.thoughtworks.xstream.converters.extended.LocaleConverter; import com.thoughtworks.xstream.converters.extended.LookAndFeelConverter; import com.thoughtworks.xstream.converters.extended.SqlDateConverter; import com.thoughtworks.xstream.converters.extended.SqlTimeConverter; import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter; import com.thoughtworks.xstream.converters.extended.TextAttributeConverter; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.ClassLoaderReference; import com.thoughtworks.xstream.core.DefaultConverterLookup; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.MapBackedDataHolder; import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy; import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy; import com.thoughtworks.xstream.core.TreeMarshallingStrategy; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.core.util.SelfStreamingInstanceChecker; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.StatefulWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.AnnotationConfiguration; import com.thoughtworks.xstream.mapper.ArrayMapper; import com.thoughtworks.xstream.mapper.AttributeAliasingMapper; import com.thoughtworks.xstream.mapper.AttributeMapper; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.ClassAliasingMapper; import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper; import com.thoughtworks.xstream.mapper.DefaultMapper; import com.thoughtworks.xstream.mapper.DynamicProxyMapper; import com.thoughtworks.xstream.mapper.ElementIgnoringMapper; import com.thoughtworks.xstream.mapper.FieldAliasingMapper; import com.thoughtworks.xstream.mapper.ImmutableTypesMapper; import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper; import com.thoughtworks.xstream.mapper.LocalConversionMapper; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.mapper.OuterClassMapper; import com.thoughtworks.xstream.mapper.PackageAliasingMapper; import com.thoughtworks.xstream.mapper.SecurityMapper; import com.thoughtworks.xstream.mapper.SystemAttributeAliasingMapper; import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper; import com.thoughtworks.xstream.security.AnyTypePermission; import com.thoughtworks.xstream.security.ArrayTypePermission; import com.thoughtworks.xstream.security.ExplicitTypePermission; import com.thoughtworks.xstream.security.InterfaceTypePermission; import com.thoughtworks.xstream.security.NoPermission; import com.thoughtworks.xstream.security.NoTypePermission; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; import com.thoughtworks.xstream.security.RegExpTypePermission; import com.thoughtworks.xstream.security.TypeHierarchyPermission; import com.thoughtworks.xstream.security.TypePermission; import com.thoughtworks.xstream.security.WildcardTypePermission; /** * Simple facade to XStream library, a Java-XML serialization tool. * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre> * * </blockquote> * <hr> * <h3>Aliasing classes</h3> * <p> * To create shorter XML, you can specify aliases for classes using the <code>alias()</code> method. For example, you * can shorten all occurrences of element <code>&lt;com.blah.MyThing&gt;</code> to <code>&lt;my-thing&gt;</code> by * registering an alias for the class. * <p> * <hr> * <blockquote> * * <pre> * xstream.alias(&quot;my-thing&quot;, MyThing.class); * </pre> * * </blockquote> * <hr> * <h3>Converters</h3> * <p> * XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each of which acts as a * strategy for converting a particular type of class to XML and back again. Out of the box, XStream contains converters * for most basic types (String, Date, int, boolean, etc) and collections (Map, List, Set, Properties, etc). For other * objects reflection is used to serialize each field recursively. * </p> * <p> * Extra converters can be registered using the <code>registerConverter()</code> method. Some non-standard converters * are supplied in the {@link com.thoughtworks.xstream.converters.extended} package and you can create your own by * implementing the {@link com.thoughtworks.xstream.converters.Converter} interface. * </p> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre> * * </blockquote> * <hr> * <p> * The converters can be registered with an explicit priority. By default they are registered with * XStream.PRIORITY_NORMAL. Converters of same priority will be used in the reverse sequence they have been registered. * The default converter, i.e. the converter which will be used if no other registered converter is suitable, can be * registered with priority XStream.PRIORITY_VERY_LOW. XStream uses by default the * {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the fallback converter. * </p> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new CustomDefaultConverter(), XStream.PRIORITY_VERY_LOW); * </pre> * * </blockquote> * <hr> * <h3>Object graphs</h3> * <p> * XStream has support for object graphs; a deserialized object graph will keep references intact, including circular * references. * </p> * <p> * XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using * <code>setMode()</code>: * </p> * <table border='1'> * <caption></caption> * <tr> * <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML with the least * clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES);</code></td> * <td>Uses XPath relative references to signify duplicate references. The XPath expression ensures that a single node * only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate references. The XPath expression ensures that a single node * only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this * is easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object structure like a tree. Duplicate references are treated * as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than * the other two modes.</td> * </tr> * </table> * <h3>Thread safety</h3> * <p> * The XStream instance is thread-safe. That is, once the XStream instance has been created and configured, it may be * shared across multiple threads allowing objects to be serialized/deserialized concurrently. <em>Note, that this only * applies if annotations are not auto-detected on-the-fly.</em> * </p> * <h3>Implicit collections</h3> * <p> * To avoid the need for special tags for collections, you can define implicit collections using one of the * <code>addImplicitCollection</code> methods. * </p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @author Guilherme Silveira */ public class XStream { // CAUTION: The sequence of the fields is intentional for an optimal XML output of a // self-serialization! private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private ClassLoaderReference classLoaderReference; private MarshallingStrategy marshallingStrategy; private ConverterLookup converterLookup; private ConverterRegistry converterRegistry; private Mapper mapper; private PackageAliasingMapper packageAliasingMapper; private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private ElementIgnoringMapper elementIgnoringMapper; private AttributeAliasingMapper attributeAliasingMapper; private SystemAttributeAliasingMapper systemAttributeAliasingMapper; private AttributeMapper attributeMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private LocalConversionMapper localConversionMapper; private SecurityMapper securityMapper; private AnnotationConfiguration annotationConfiguration; private transient boolean securityInitialized; private transient boolean securityWarningGiven; public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_RELATIVE_REFERENCES = 1003; public static final int XPATH_ABSOLUTE_REFERENCES = 1004; public static final int SINGLE_NODE_XPATH_RELATIVE_REFERENCES = 1005; public static final int SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES = 1006; public static final int PRIORITY_VERY_HIGH = 10000; public static final int PRIORITY_NORMAL = 0; public static final int PRIORITY_LOW = -10; public static final int PRIORITY_VERY_LOW = -20; private static final String ANNOTATION_MAPPER_TYPE = "com.thoughtworks.xstream.mapper.AnnotationMapper"; private static final Pattern IGNORE_ALL = Pattern.compile(".*"); private static final Pattern LAZY_ITERATORS = Pattern.compile(".*\\$LazyIterator"); private static final Pattern JAVAX_CRYPTO = Pattern.compile("javax\\.crypto\\..*"); /** * Constructs a default XStream. * <p> * The instance will use the {@link XppDriver} as default and tries to determine the best match for the * {@link ReflectionProvider} on its own. * </p> * * @throws InitializationException in case of an initialization problem */ public XStream() { this(null, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link ReflectionProvider}. * <p> * The instance will use the {@link XppDriver} as default. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching reflection provider * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}. * <p> * The instance will tries to determine the best match for the {@link ReflectionProvider} on its own. * </p> * * @param hierarchicalStreamDriver the driver instance * @throws InitializationException in case of an initialization problem */ public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param hierarchicalStreamDriver the driver instance * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and a prepared * {@link Mapper} chain. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param driver the driver instance * @throws InitializationException in case of an initialization problem * @deprecated As of 1.3, use {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoader, Mapper)} * instead */ public XStream(ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { this(reflectionProvider, driver, new CompositeClassLoader(), mapper); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and a * {@link ClassLoaderReference}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference) { this(reflectionProvider, driver, classLoaderReference, null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider} and the * {@link ClassLoader} to use. * * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference)} */ public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { this(reflectionProvider, driver, classLoader, null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain and the {@link ClassLoader} to use. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoader the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use * {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference, Mapper)} */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, new DefaultConverterLookup()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain and the {@link ClassLoaderReference}. * <p> * The {@link ClassLoaderReference} should also be used for the {@link Mapper} chain. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper) { this(reflectionProvider, driver, classLoaderReference, mapper, new DefaultConverterLookup()); } private XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoader, Mapper mapper, final DefaultConverterLookup defaultConverterLookup) { this(reflectionProvider, driver, classLoader, mapper, new ConverterLookup() { public Converter lookupConverterForType(Class type) { return defaultConverterLookup.lookupConverterForType(type); } }, new ConverterRegistry() { public void registerConverter(Converter converter, int priority) { defaultConverterLookup.registerConverter(converter, priority); } }); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain, the {@link ClassLoaderReference} and an own {@link ConverterLookup} and * {@link ConverterRegistry}. * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoader the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param converterLookup the instance that is used to lookup the converters * @param converterRegistry an instance to manage the converter instances * @throws InitializationException in case of an initialization problem * @since 1.3 * @deprecated As of 1.4.5 use * {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoaderReference, Mapper, ConverterLookup, ConverterRegistry)} */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, converterLookup, converterRegistry); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared * {@link Mapper} chain, the {@link ClassLoaderReference} and an own {@link ConverterLookup} and * {@link ConverterRegistry}. * <p> * The ClassLoaderReference should also be used for the Mapper chain. The ConverterLookup should access the * ConverterRegistry if you intent to register {@link Converter} instances with XStream facade or you are using * annotations. * </p> * * @param reflectionProvider the reflection provider to use or <em>null</em> for best matching Provider * @param driver the driver instance * @param classLoaderReference the reference to the {@link ClassLoader} to use * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default chain * @param converterLookup the instance that is used to lookup the converters * @param converterRegistry an instance to manage the converter instances or <em>null</em> to prevent any further * registry (including annotations) * @throws InitializationException in case of an initialization problem * @since 1.4.5 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { if (reflectionProvider == null) { reflectionProvider = JVM.newReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = classLoaderReference; this.converterLookup = converterLookup; this.converterRegistry = converterRegistry; this.mapper = mapper == null ? buildMapper() : mapper; setupMappers(); setupSecurity(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if (useXStream11XmlFriendlyMapper()) { mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new DynamicProxyMapper(mapper); mapper = new PackageAliasingMapper(mapper); mapper = new ClassAliasingMapper(mapper); mapper = new ElementIgnoringMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new SystemAttributeAliasingMapper(mapper); mapper = new ImplicitCollectionMapper(mapper, reflectionProvider); mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider); if (JVM.isVersion(5)) { mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.EnumMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new LocalConversionMapper(mapper); mapper = new ImmutableTypesMapper(mapper); if (JVM.isVersion(8)) { mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.LambdaMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new SecurityMapper(mapper); if (JVM.isVersion(5)) { mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{ Mapper.class, ConverterRegistry.class, ConverterLookup.class, ClassLoaderReference.class, ReflectionProvider.class}, new Object[]{ mapper, converterRegistry, converterLookup, classLoaderReference, reflectionProvider}); } mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } private Mapper buildMapperDynamically(String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate mapper : " + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate mapper : " + className, e); } } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } /** * @deprecated As of 1.4.8 */ protected boolean useXStream11XmlFriendlyMapper() { return false; } private void setupMappers() { packageAliasingMapper = (PackageAliasingMapper)this.mapper.lookupMapperOfType(PackageAliasingMapper.class); classAliasingMapper = (ClassAliasingMapper)this.mapper.lookupMapperOfType(ClassAliasingMapper.class); elementIgnoringMapper = (ElementIgnoringMapper)this.mapper.lookupMapperOfType(ElementIgnoringMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper.lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper .lookupMapperOfType(SystemAttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper.lookupMapperOfType(ImmutableTypesMapper.class); localConversionMapper = (LocalConversionMapper)this.mapper.lookupMapperOfType(LocalConversionMapper.class); securityMapper = (SecurityMapper)this.mapper.lookupMapperOfType(SecurityMapper.class); annotationConfiguration = (AnnotationConfiguration)this.mapper .lookupMapperOfType(AnnotationConfiguration.class); } protected void setupSecurity() { if (securityMapper == null) { return; } addPermission(AnyTypePermission.ANY); denyTypes(new String[]{"java.beans.EventHandler", "javax.imageio.ImageIO$ContainsFilter"}); denyTypesByRegExp(new Pattern[]{LAZY_ITERATORS, JAVAX_CRYPTO}); allowTypeHierarchy(Exception.class); securityInitialized = false; } /** * Setup the security framework of a XStream instance. * <p> * This method is a pure helper method for XStream 1.4.x. It initializes an XStream instance with a white list of * well-known and simply types of the Java runtime as it is done in XStream 1.5.x by default. This method will do * therefore nothing in XStream 1.5. * </p> * * @param xstream * @since 1.4.10 */ public static void setupDefaultSecurity(final XStream xstream) { if (!xstream.securityInitialized) { xstream.addPermission(NoTypePermission.NONE); xstream.addPermission(NullPermission.NULL); xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); xstream.addPermission(ArrayTypePermission.ARRAYS); xstream.addPermission(InterfaceTypePermission.INTERFACES); xstream.allowTypeHierarchy(Calendar.class); xstream.allowTypeHierarchy(Collection.class); xstream.allowTypeHierarchy(Map.class); xstream.allowTypeHierarchy(Map.Entry.class); xstream.allowTypeHierarchy(Member.class); xstream.allowTypeHierarchy(Number.class); xstream.allowTypeHierarchy(Throwable.class); xstream.allowTypeHierarchy(TimeZone.class); Class type = JVM.loadClassForName("java.lang.Enum"); if (type != null) { xstream.allowTypeHierarchy(type); } type = JVM.loadClassForName("java.nio.file.Path"); if (type != null) { xstream.allowTypeHierarchy(type); } final Set types = new HashSet(); types.add(BitSet.class); types.add(Charset.class); types.add(Class.class); types.add(Currency.class); types.add(Date.class); types.add(DecimalFormatSymbols.class); types.add(File.class); types.add(Locale.class); types.add(Object.class); types.add(Pattern.class); types.add(StackTraceElement.class); types.add(String.class); types.add(StringBuffer.class); types.add(JVM.loadClassForName("java.lang.StringBuilder")); types.add(URL.class); types.add(URI.class); types.add(JVM.loadClassForName("java.util.UUID")); if (JVM.isSQLAvailable()) { types.add(JVM.loadClassForName("java.sql.Timestamp")); types.add(JVM.loadClassForName("java.sql.Time")); types.add(JVM.loadClassForName("java.sql.Date")); } if (JVM.isVersion(8)) { xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.Clock")); types.add(JVM.loadClassForName("java.time.Duration")); types.add(JVM.loadClassForName("java.time.Instant")); types.add(JVM.loadClassForName("java.time.LocalDate")); types.add(JVM.loadClassForName("java.time.LocalDateTime")); types.add(JVM.loadClassForName("java.time.LocalTime")); types.add(JVM.loadClassForName("java.time.MonthDay")); types.add(JVM.loadClassForName("java.time.OffsetDateTime")); types.add(JVM.loadClassForName("java.time.OffsetTime")); types.add(JVM.loadClassForName("java.time.Period")); types.add(JVM.loadClassForName("java.time.Ser")); types.add(JVM.loadClassForName("java.time.Year")); types.add(JVM.loadClassForName("java.time.YearMonth")); types.add(JVM.loadClassForName("java.time.ZonedDateTime")); xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.ZoneId")); types.add(JVM.loadClassForName("java.time.chrono.HijrahDate")); types.add(JVM.loadClassForName("java.time.chrono.JapaneseDate")); types.add(JVM.loadClassForName("java.time.chrono.JapaneseEra")); types.add(JVM.loadClassForName("java.time.chrono.MinguoDate")); types.add(JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate")); types.add(JVM.loadClassForName("java.time.chrono.Ser")); xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.chrono.Chronology")); types.add(JVM.loadClassForName("java.time.temporal.ValueRange")); types.add(JVM.loadClassForName("java.time.temporal.WeekFields")); } types.remove(null); final Iterator iter = types.iterator(); final Class[] classes = new Class[types.size()]; for (int i = 0; i < classes.length; ++i) { classes[i] = (Class)iter.next(); } xstream.allowTypes(classes); } else { throw new IllegalArgumentException("Security framework of XStream instance already initialized"); } } protected void setupAliases() { if (classAliasingMapper == null) { return; } alias("null", Mapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("field", Field.class); alias("date", Date.class); alias("uri", URI.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("sorted-set", SortedSet.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); alias("empty-list", Collections.EMPTY_LIST.getClass()); alias("empty-map", Collections.EMPTY_MAP.getClass()); alias("empty-set", Collections.EMPTY_SET.getClass()); alias("singleton-list", Collections.singletonList(this).getClass()); alias("singleton-map", Collections.singletonMap(this, null).getClass()); alias("singleton-set", Collections.singleton(this).getClass()); if (JVM.isAWTAvailable()) { // Instantiating these two classes starts the AWT system, which is undesirable. // Calling loadClass ensures a reference to the class is found but they are not // instantiated. alias("awt-color", JVM.loadClassForName("java.awt.Color", false)); alias("awt-font", JVM.loadClassForName("java.awt.Font", false)); alias("awt-text-attribute", JVM.loadClassForName("java.awt.font.TextAttribute")); } Class type = JVM.loadClassForName("javax.activation.ActivationDataFlavor"); if (type != null) { alias("activation-data-flavor", type); } if (JVM.isSQLAvailable()) { alias("sql-timestamp", JVM.loadClassForName("java.sql.Timestamp")); alias("sql-time", JVM.loadClassForName("java.sql.Time")); alias("sql-date", JVM.loadClassForName("java.sql.Date")); } alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); if (JVM.isVersion(4)) { aliasDynamically("auth-subject", "javax.security.auth.Subject"); alias("linked-hash-map", JVM.loadClassForName("java.util.LinkedHashMap")); alias("linked-hash-set", JVM.loadClassForName("java.util.LinkedHashSet")); alias("trace", JVM.loadClassForName("java.lang.StackTraceElement")); alias("currency", JVM.loadClassForName("java.util.Currency")); aliasType("charset", JVM.loadClassForName("java.nio.charset.Charset")); } if (JVM.isVersion(5)) { aliasDynamically("xml-duration", "javax.xml.datatype.Duration"); alias("concurrent-hash-map", JVM.loadClassForName("java.util.concurrent.ConcurrentHashMap")); alias("enum-set", JVM.loadClassForName("java.util.EnumSet")); alias("enum-map", JVM.loadClassForName("java.util.EnumMap")); alias("string-builder", JVM.loadClassForName("java.lang.StringBuilder")); alias("uuid", JVM.loadClassForName("java.util.UUID")); } if (JVM.isVersion(7)) { aliasType("path", JVM.loadClassForName("java.nio.file.Path")); } if (JVM.isVersion(8)) { alias("fixed-clock", JVM.loadClassForName("java.time.Clock$FixedClock")); alias("offset-clock", JVM.loadClassForName("java.time.Clock$OffsetClock")); alias("system-clock", JVM.loadClassForName("java.time.Clock$SystemClock")); alias("tick-clock", JVM.loadClassForName("java.time.Clock$TickClock")); alias("day-of-week", JVM.loadClassForName("java.time.DayOfWeek")); alias("duration", JVM.loadClassForName("java.time.Duration")); alias("instant", JVM.loadClassForName("java.time.Instant")); alias("local-date", JVM.loadClassForName("java.time.LocalDate")); alias("local-date-time", JVM.loadClassForName("java.time.LocalDateTime")); alias("local-time", JVM.loadClassForName("java.time.LocalTime")); alias("month", JVM.loadClassForName("java.time.Month")); alias("month-day", JVM.loadClassForName("java.time.MonthDay")); alias("offset-date-time", JVM.loadClassForName("java.time.OffsetDateTime")); alias("offset-time", JVM.loadClassForName("java.time.OffsetTime")); alias("period", JVM.loadClassForName("java.time.Period")); alias("year", JVM.loadClassForName("java.time.Year")); alias("year-month", JVM.loadClassForName("java.time.YearMonth")); alias("zoned-date-time", JVM.loadClassForName("java.time.ZonedDateTime")); aliasType("zone-id", JVM.loadClassForName("java.time.ZoneId")); aliasType("chronology", JVM.loadClassForName("java.time.chrono.Chronology")); alias("hijrah-date", JVM.loadClassForName("java.time.chrono.HijrahDate")); alias("hijrah-era", JVM.loadClassForName("java.time.chrono.HijrahEra")); alias("japanese-date", JVM.loadClassForName("java.time.chrono.JapaneseDate")); alias("japanese-era", JVM.loadClassForName("java.time.chrono.JapaneseEra")); alias("minguo-date", JVM.loadClassForName("java.time.chrono.MinguoDate")); alias("minguo-era", JVM.loadClassForName("java.time.chrono.MinguoEra")); alias("thai-buddhist-date", JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate")); alias("thai-buddhist-era", JVM.loadClassForName("java.time.chrono.ThaiBuddhistEra")); alias("chrono-field", JVM.loadClassForName("java.time.temporal.ChronoField")); alias("chrono-unit", JVM.loadClassForName("java.time.temporal.ChronoUnit")); alias("iso-field", JVM.loadClassForName("java.time.temporal.IsoFields$Field")); alias("iso-unit", JVM.loadClassForName("java.time.temporal.IsoFields$Unit")); alias("julian-field", JVM.loadClassForName("java.time.temporal.JulianFields$Field")); alias("temporal-value-range", JVM.loadClassForName("java.time.temporal.ValueRange")); alias("week-fields", JVM.loadClassForName("java.time.temporal.WeekFields")); } if (JVM.loadClassForName("java.lang.invoke.SerializedLambda") != null) { aliasDynamically("serialized-lambda", "java.lang.invoke.SerializedLambda"); } } private void aliasDynamically(String alias, String className) { Class type = JVM.loadClassForName(className); if (type != null) { alias(alias, type); } } protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(TreeSet.class, SortedSet.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { registerConverter(new ReflectionConverter(mapper, reflectionProvider), PRIORITY_VERY_LOW); registerConverter(new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URIConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonCollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter((Converter)new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if (JVM.isSQLAvailable()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL); if (JVM.isAWTAvailable()) { registerConverter(new FontConverter(mapper), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } if (JVM.isSwingAvailable()) { registerConverter(new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.isVersion(4)) { // late bound converters - allows XStream to be compiled on earlier JDKs registerConverterDynamically("com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[]{ConverterLookup.class}, new Object[]{converterLookup}); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(5)) { // late bound converters - allows XStream to be compiled on earlier JDKs if (JVM.loadClassForName("javax.xml.datatype.Duration") != null) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.DurationConverter", PRIORITY_NORMAL, null, null); } registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.basic.StringBuilderConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.basic.UUIDConverter", PRIORITY_NORMAL, null, null); } if (JVM.loadClassForName("javax.activation.ActivationDataFlavor") != null) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.ActivationDataFlavorConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(7)) { registerConverterDynamically("com.thoughtworks.xstream.converters.extended.PathConverter", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(8)) { registerConverterDynamically("com.thoughtworks.xstream.converters.time.ChronologyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.DurationConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.HijrahDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseEraConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.InstantConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.MinguoDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.MonthDayConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.PeriodConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.SystemClockConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ValueRangeConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.WeekFieldsConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearMonthConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZoneIdConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically("com.thoughtworks.xstream.converters.reflection.LambdaConverter", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class, ClassLoaderReference.class}, new Object[]{mapper, reflectionProvider, classLoaderReference}); } registerConverter(new SelfStreamingInstanceChecker(converterLookup, this), PRIORITY_NORMAL); } private void registerConverterDynamically(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate converter : " + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException("Could not instantiate converter : " + className, e); } } protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class, false); addImmutableType(Boolean.class, false); addImmutableType(byte.class, false); addImmutableType(Byte.class, false); addImmutableType(char.class, false); addImmutableType(Character.class, false); addImmutableType(double.class, false); addImmutableType(Double.class, false); addImmutableType(float.class, false); addImmutableType(Float.class, false); addImmutableType(int.class, false); addImmutableType(Integer.class, false); addImmutableType(long.class, false); addImmutableType(Long.class, false); addImmutableType(short.class, false); addImmutableType(Short.class, false); // additional types addImmutableType(Mapper.Null.class, false); addImmutableType(BigDecimal.class, false); addImmutableType(BigInteger.class, false); addImmutableType(String.class, false); addImmutableType(URL.class, false); addImmutableType(File.class, false); addImmutableType(Class.class, false); if (JVM.isVersion(7)) { Class type = JVM.loadClassForName("java.nio.file.Paths"); if (type != null) { Method methodGet; try { methodGet = type.getDeclaredMethod("get", new Class[]{String.class, String[].class}); if (methodGet != null) { Object path = methodGet.invoke(null, new Object[]{".", new String[0]}); if (path != null) { addImmutableType(path.getClass(), false); } } } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } if (JVM.isAWTAvailable()) { addImmutableTypeDynamically("java.awt.font.TextAttribute", false); } if (JVM.isVersion(4)) { // late bound types - allows XStream to be compiled on earlier JDKs addImmutableTypeDynamically("java.nio.charset.Charset", true); addImmutableTypeDynamically("java.util.Currency", true); } if (JVM.isVersion(5)) { addImmutableTypeDynamically("java.util.UUID", true); } addImmutableType(URI.class, true); addImmutableType(Collections.EMPTY_LIST.getClass(), true); addImmutableType(Collections.EMPTY_SET.getClass(), true); addImmutableType(Collections.EMPTY_MAP.getClass(), true); if (JVM.isVersion(8)) { addImmutableTypeDynamically("java.time.Duration", false); addImmutableTypeDynamically("java.time.Instant", false); addImmutableTypeDynamically("java.time.LocalDate", false); addImmutableTypeDynamically("java.time.LocalDateTime", false); addImmutableTypeDynamically("java.time.LocalTime", false); addImmutableTypeDynamically("java.time.MonthDay", false); addImmutableTypeDynamically("java.time.OffsetDateTime", false); addImmutableTypeDynamically("java.time.OffsetTime", false); addImmutableTypeDynamically("java.time.Period", false); addImmutableTypeDynamically("java.time.Year", false); addImmutableTypeDynamically("java.time.YearMonth", false); addImmutableTypeDynamically("java.time.ZonedDateTime", false); addImmutableTypeDynamically("java.time.ZoneId", false); addImmutableTypeDynamically("java.time.ZoneOffset", false); addImmutableTypeDynamically("java.time.ZoneRegion", false); addImmutableTypeDynamically("java.time.chrono.HijrahChronology", false); addImmutableTypeDynamically("java.time.chrono.HijrahDate", false); addImmutableTypeDynamically("java.time.chrono.IsoChronology", false); addImmutableTypeDynamically("java.time.chrono.JapaneseChronology", false); addImmutableTypeDynamically("java.time.chrono.JapaneseDate", false); addImmutableTypeDynamically("java.time.chrono.JapaneseEra", false); addImmutableTypeDynamically("java.time.chrono.MinguoChronology", false); addImmutableTypeDynamically("java.time.chrono.MinguoDate", false); addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistChronology", false); addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistDate", false); addImmutableTypeDynamically("java.time.temporal.IsoFields$Field", false); addImmutableTypeDynamically("java.time.temporal.IsoFields$Unit", false); addImmutableTypeDynamically("java.time.temporal.JulianFields$Field", false); } } private void addImmutableTypeDynamically(String className, boolean isReferenceable) { Class type = JVM.loadClassForName(className); if (type != null) { addImmutableType(type, isReferenceable); } } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. * * @throws XStreamException if the object cannot be serialized */ public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. The Writer will be flushed afterwards and in case * of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize an object to the given OutputStream as pretty-printed XML. The OutputStream will be flushed afterwards * and in case of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize and object to a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, * XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } /** * Deserialize an object from an XML String. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader reader) { return unmarshal(hierarchicalStreamDriver.createReader(reader), null); } /** * Deserialize an object from an XML InputStream. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } /** * Deserialize an object from a URL. Depending on the parser implementation, some might take the file path as * SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(URL url) { return fromXML(url, null); } /** * Deserialize an object from a file. Depending on the parser implementation, some might take the file path as * SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(File file) { return fromXML(file, null); } /** * Deserialize an object from an XML String, populating the fields of the given root object instead of instantiating * a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into * the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, populating the fields of the given root object instead of instantiating * a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into * the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a URL, populating the fields of the given root object instead of instantiating a new * one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw * memory area of the existing object. Use with care! Depending on the parser implementation, some might take the * file path as SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(URL url, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(url), root); } /** * Deserialize an object from a file, populating the fields of the given root object instead of instantiating a new * one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw * memory area of the existing object. Use with care! Depending on the parser implementation, some might take the * file path as SystemId to resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since 1.4 */ public Object fromXML(File file, Object root) { HierarchicalStreamReader reader = hierarchicalStreamDriver.createReader(file); try { return unmarshal(reader, root); } finally { reader.close(); } } /** * Deserialize an object from an XML InputStream, populating the fields of the given root object instead of * instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write * directly into the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(input), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), populating the fields of the given root * object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter * XStream will write directly into the raw memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed to XStream creating a new * instance. Note, that this is a special use case! With the ReflectionConverter XStream will write * directly into the raw memory area of the existing object. Use with care! * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, * XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { try { if (!securityInitialized && !securityWarningGiven) { securityWarningGiven = true; System.err .println( "Security framework of XStream not explicitly initialized, using predefined black list on your own risk."); } return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper); } catch (ConversionException e) { Package pkg = getClass().getPackage(); String version = pkg != null ? pkg.getImplementationVersion() : null; e.add("version", version != null ? version : "not available"); throw e; } } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addClassAlias(name, type); } /** * Alias a type to a shorter name to be used in XML elements. Any class that is assignable to this type will be * aliased to the same name. * * @param name Short name * @param type Type to be aliased * @since 1.2 * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addTypeAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is * available */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } /** * Alias a package to a shorter name to be used in XML elements. * * @param name Short name * @param pkgName package to be aliased * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link PackageAliasingMapper} is * available * @since 1.3.1 */ public void aliasPackage(String name, String pkgName) { if (packageAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + PackageAliasingMapper.class.getName() + " available"); } packageAliasingMapper.addPackageAlias(name, pkgName); } /** * Create an alias for a field name. * * @param alias the alias itself * @param definedIn the type that declares the field * @param fieldName the name of the field * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void aliasField(String alias, Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName); } /** * Create an alias for an attribute * * @param alias the alias itself * @param attributeName the name of the attribute * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(attributeName, alias); } /** * Create an alias for a system attribute. XStream will not write a system attribute if its alias is set to * <code>null</code>. However, this is not reversible, i.e. deserialization of the result is likely to fail * afterwards and will not produce an object equal to the originally written one. * * @param alias the alias itself (may be <code>null</code>) * @param systemAttributeName the name of the system attribute * @throws InitializationException if no {@link SystemAttributeAliasingMapper} is available * @since 1.3.1 */ public void aliasSystemAttribute(String alias, String systemAttributeName) { if (systemAttributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + SystemAttributeAliasingMapper.class.getName() + " available"); } systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias); } /** * Create an alias for an attribute. * * @param definedIn the type where the attribute is defined * @param attributeName the name of the attribute * @param alias the alias itself * @throws InitializationException if no {@link AttributeAliasingMapper} is available * @since 1.2.2 */ public void aliasAttribute(Class definedIn, String attributeName, String alias) { aliasField(alias, definedIn, attributeName); useAttributeFor(definedIn, attributeName); } /** * Use an attribute for a field or a specific type. * * @param fieldName the name of the field * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(fieldName, type); } /** * Use an attribute for a field declared in a specific type. * * @param fieldName the name of the field * @param definedIn the Class containing such field * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2.2 */ public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(definedIn, fieldName); } /** * Use an attribute for an arbitrary type. * * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(type); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters an instance of this * type, it will use the default implementation instead. For example, java.util.ArrayList is the default * implementation of java.util.List. * * @param defaultImplementation * @param ofType * @throws InitializationException if no {@link DefaultImplementationsMapper} is available */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + DefaultImplementationsMapper.class.getName() + " available"); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } /** * Add immutable types. The value of the instances of these types will always be written into the stream even if * they appear multiple times. However, references are still supported at deserialization time. * * @throws InitializationException if no {@link ImmutableTypesMapper} is available * @deprecated As of 1.4.9 use {@link #addImmutableType(Class, boolean)} */ public void addImmutableType(Class type) { addImmutableType(type, true); } /** * Add immutable types. The value of the instances of these types will always be written into the stream even if * they appear multiple times. * <p> * Note, while a reference-keeping marshaller will not write references for immutable types into the stream, a * reference-keeping unmarshaller can still support such references in the stream for compatibility reasons at the * expense of memory consumption. Therefore declare these types only as referenceable if your already persisted * streams do contain such references. Otherwise you may waste a lot of memory during deserialization. * </p> * * @param isReferenceable <code>true</code> if support at deserialization time is required for compatibility at the * cost of a higher memory footprint, <code>false</code> otherwise * @throws InitializationException if no {@link ImmutableTypesMapper} is available * @since 1.4.9 */ public void addImmutableType(final Class type, final boolean isReferenceable) { if (immutableTypesMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImmutableTypesMapper.class.getName() + " available"); } immutableTypesMapper.addImmutableType(type, isReferenceable); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(converter, priority); } } public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(SingleValueConverter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(new SingleValueConverterWrapper(converter), priority); } } /** * Register a local {@link Converter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) { if (localConversionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + LocalConversionMapper.class.getName() + " available"); } localConversionMapper.registerLocalConverter(definedIn, fieldName, converter); } /** * Register a local {@link SingleValueConverter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) { registerLocalConverter(definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter)); } /** * Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}. * * @return the mapper * @since 1.2 */ public Mapper getMapper() { return mapper; } /** * Retrieve the {@link ReflectionProvider} in use. * * @return the mapper * @since 1.2.1 */ public ReflectionProvider getReflectionProvider() { return reflectionProvider; } public ConverterLookup getConverterLookup() { return converterLookup; } /** * Change mode for dealing with duplicate references. Valid values are <code>XPATH_ABSOLUTE_REFERENCES</code>, * <code>XPATH_RELATIVE_REFERENCES</code>, <code>XStream.ID_REFERENCES</code> and * <code>XStream.NO_REFERENCES</code>. * * @throws IllegalArgumentException if the mode is not one of the declared types * @see #XPATH_ABSOLUTE_REFERENCES * @see #XPATH_RELATIVE_REFERENCES * @see #ID_REFERENCES * @see #NO_REFERENCES */ public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; case SINGLE_NODE_XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(ReferenceByXPathMarshallingStrategy.RELATIVE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; case SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(ReferenceByXPathMarshallingStrategy.ABSOLUTE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * Adds a default implicit collection which is used for any unmapped XML tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. */ public void addImplicitCollection(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName, null, null); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. * @param itemType type of the items to be part of this collection * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete collection type or matching * the default implementation type of the collection type. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { addImplicitMap(ownerType, fieldName, itemFieldName, itemType, null); } /** * Adds an implicit array. * * @param ownerType class owning the implicit array * @param fieldName name of the array field * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } /** * Adds an implicit array which is used for all items of the given itemType when the array type matches. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemType type of the items to be part of this array * @throws InitializationException if no {@link ImplicitCollectionMapper} is available or the array type does not * match the itemType * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, itemType); } /** * Adds an implicit array which is used for all items of the given element name defined by itemName. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemName alias name of the items * @throws InitializationException if no {@link ImplicitCollectionMapper} is available * @since 1.4 */ public void addImplicitArray(Class ownerType, String fieldName, String itemName) { addImplicitCollection(ownerType, fieldName, itemName, null); } /** * Adds an implicit map. * * @param ownerType class owning the implicit map * @param fieldName name of the field in the ownerType. This field must be a concrete map type or matching the * default implementation type of the map type. * @param itemType type of the items to be part of this map as value * @param keyFieldName the name of the field of the itemType that is used for the key in the map * @since 1.4 */ public void addImplicitMap(Class ownerType, String fieldName, Class itemType, String keyFieldName) { addImplicitMap(ownerType, fieldName, null, itemType, keyFieldName); } /** * Adds an implicit map. * * @param ownerType class owning the implicit map * @param fieldName name of the field in the ownerType. This field must be a concrete map type or matching the * default implementation type of the map type. * @param itemName alias name of the items * @param itemType type of the items to be part of this map as value * @param keyFieldName the name of the field of the itemType that is used for the key in the map * @since 1.4 */ public void addImplicitMap(Class ownerType, String fieldName, String itemName, Class itemType, String keyFieldName) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, itemName, itemType, keyFieldName); } /** * Create a DataHolder that can be used to pass data to the converters. The DataHolder is provided with a call to * {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)}, * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}, * {@link #createObjectInputStream(HierarchicalStreamReader, DataHolder)} or * {@link #createObjectOutputStream(HierarchicalStreamWriter, String, DataHolder)}. * * @return a new {@link DataHolder} */ public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName) throws IOException { return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * <p> * Because an ObjectOutputStream can contain multiple items and XML only allows a single root node, the stream must * be written inside an enclosing node. * </p> * <p> * It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be incomplete. * </p> * <h3>Example</h3> * * <pre> * ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, &quot;things&quot;); * out.writeInt(123); * out.writeObject(&quot;Hello&quot;); * out.writeObject(someObject) * out.close(); * </pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName) throws IOException { return createObjectOutputStream(writer, rootNodeName, null); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.4.10 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName, final DataHolder dataHolder) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(final Object object) { marshal(object, statefulWriter, dataHolder); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from an InputStream using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.3 */ public ObjectInputStream createObjectInputStream(InputStream in) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(in)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * <p> * It is necessary to call ObjectInputStream.close() when done, otherwise the stream might keep system resources. * </p> * <h3>Example</h3> * * <pre> * ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject(); * </pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return createObjectInputStream(reader, null); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.4.10 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); final Object result = unmarshal(reader, null, dataHolder); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }, classLoaderReference); } /** * Change the ClassLoader XStream uses to load classes. Creating an XStream instance it will register for all kind * of classes and types of the current JDK, but not for any 3rd party type. To ensure that all other types are * loaded with your class loader, you should call this method as early as possible - or consider to provide the * class loader directly in the constructor. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Retrieve the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } /** * Retrieve the reference to this instance' ClassLoader. Use this reference for other XStream components (like * converters) to ensure that they will use a changed ClassLoader instance automatically. * * @return the reference * @since 1.4.5 */ public ClassLoaderReference getClassLoaderReference() { return classLoaderReference; } /** * Prevents a field from being serialized. To omit a field you must always provide the declaring type and not * necessarily the type that is converted. * * @since 1.1.3 * @throws InitializationException if no {@link ElementIgnoringMapper} is available */ public void omitField(Class definedIn, String fieldName) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ElementIgnoringMapper.class.getName() + " available"); } elementIgnoringMapper.omitField(definedIn, fieldName); } /** * Ignore all unknown elements. * * @since 1.4.5 */ public void ignoreUnknownElements() { ignoreUnknownElements(IGNORE_ALL); } /** * Add pattern for unknown element names to ignore. * * @param pattern the name pattern as regular expression * @since 1.4.5 */ public void ignoreUnknownElements(String pattern) { ignoreUnknownElements(Pattern.compile(pattern)); } /** * Add pattern for unknown element names to ignore. * * @param pattern the name pattern as regular expression * @since 1.4.5 */ public void ignoreUnknownElements(final Pattern pattern) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ElementIgnoringMapper.class.getName() + " available"); } elementIgnoringMapper.addElementsToIgnore(pattern); } /** * Process the annotations of the given types and configure the XStream. * * @param types the types with XStream annotations * @since 1.3 */ public void processAnnotations(final Class[] types) { if (annotationConfiguration == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ANNOTATION_MAPPER_TYPE + " available"); } annotationConfiguration.processAnnotations(types); } /** * Process the annotations of the given type and configure the XStream. A call of this method will automatically * turn the auto-detection mode for annotations off. * * @param type the type with XStream annotations * @since 1.3 */ public void processAnnotations(final Class type) { processAnnotations(new Class[]{type}); } /** * Set the auto-detection mode of the AnnotationMapper. Note that auto-detection implies that the XStream is * configured while it is processing the XML steams. This is a potential concurrency problem. Also is it technically * not possible to detect all class aliases at deserialization. You have been warned! * * @param mode <code>true</code> if annotations are auto-detected * @since 1.3 */ public void autodetectAnnotations(boolean mode) { if (annotationConfiguration != null) { annotationConfiguration.autodetectAnnotations(mode); } } /** * Add a new security permission. * <p> * Permissions are evaluated in the added sequence. An instance of {@link NoTypePermission} or * {@link AnyTypePermission} will implicitly wipe any existing permission. * </p> * * @param permission the permission to add * @since 1.4.7 */ public void addPermission(TypePermission permission) { if (securityMapper != null) { securityInitialized |= permission.equals(NoTypePermission.NONE) || permission.equals(AnyTypePermission.ANY); securityMapper.addPermission(permission); } } /** * Add security permission for explicit types by name. * * @param names the type names to allow * @since 1.4.7 */ public void allowTypes(String[] names) { addPermission(new ExplicitTypePermission(names)); } /** * Add security permission for explicit types. * * @param types the types to allow * @since 1.4.7 */ public void allowTypes(Class[] types) { addPermission(new ExplicitTypePermission(types)); } /** * Add security permission for a type hierarchy. * * @param type the base type to allow * @since 1.4.7 */ public void allowTypeHierarchy(Class type) { addPermission(new TypeHierarchyPermission(type)); } /** * Add security permission for types matching one of the specified regular expressions. * * @param regexps the regular expressions to allow type names * @since 1.4.7 */ public void allowTypesByRegExp(String[] regexps) { addPermission(new RegExpTypePermission(regexps)); } /** * Add security permission for types matching one of the specified regular expressions. * * @param regexps the regular expressions to allow type names * @since 1.4.7 */ public void allowTypesByRegExp(Pattern[] regexps) { addPermission(new RegExpTypePermission(regexps)); } /** * Add security permission for types matching one of the specified wildcard patterns. * <p> * Supported are patterns with path expressions using dot as separator: * </p> * <ul> * <li>?: one non-control character except separator, e.g. for 'java.net.Inet?Address'</li> * <li>*: arbitrary number of non-control characters except separator, e.g. for types in a package like * 'java.lang.*'</li> * <li>**: arbitrary number of non-control characters including separator, e.g. for types in a package and * subpackages like 'java.lang.**'</li> * </ul> * * @param patterns the patterns to allow type names * @since 1.4.7 */ public void allowTypesByWildcard(String[] patterns) { addPermission(new WildcardTypePermission(patterns)); } /** * Add security permission denying another one. * * @param permission the permission to deny * @since 1.4.7 */ public void denyPermission(TypePermission permission) { addPermission(new NoPermission(permission)); } /** * Add security permission forbidding explicit types by name. * * @param names the type names to forbid * @since 1.4.7 */ public void denyTypes(String[] names) { denyPermission(new ExplicitTypePermission(names)); } /** * Add security permission forbidding explicit types. * * @param types the types to forbid * @since 1.4.7 */ public void denyTypes(Class[] types) { denyPermission(new ExplicitTypePermission(types)); } /** * Add security permission forbidding a type hierarchy. * * @param type the base type to forbid * @since 1.4.7 */ public void denyTypeHierarchy(Class type) { denyPermission(new TypeHierarchyPermission(type)); } /** * Add security permission forbidding types matching one of the specified regular expressions. * * @param regexps the regular expressions to forbid type names * @since 1.4.7 */ public void denyTypesByRegExp(String[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } /** * Add security permission forbidding types matching one of the specified regular expressions. * * @param regexps the regular expressions to forbid type names * @since 1.4.7 */ public void denyTypesByRegExp(Pattern[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } /** * Add security permission forbidding types matching one of the specified wildcard patterns. * <p> * Supported are patterns with path expressions using dot as separator: * </p> * <ul> * <li>?: one non-control character except separator, e.g. for 'java.net.Inet?Address'</li> * <li>*: arbitrary number of non-control characters except separator, e.g. for types in a package like * 'java.lang.*'</li> * <li>**: arbitrary number of non-control characters including separator, e.g. for types in a package and * subpackages like 'java.lang.**'</li> * </ul> * * @param patterns the patterns to forbid names * @since 1.4.7 */ public void denyTypesByWildcard(String[] patterns) { denyPermission(new WildcardTypePermission(patterns)); } private Object readResolve() { securityWarningGiven = true; return this; } /** * @deprecated As of 1.3, use {@link com.thoughtworks.xstream.InitializationException} instead */ public static class InitializationException extends XStreamException { /** * @deprecated As of 1.3, use * {@link com.thoughtworks.xstream.InitializationException#InitializationException(String, Throwable)} * instead */ public InitializationException(String message, Throwable cause) { super(message, cause); } /** * @deprecated As of 1.3, use * {@link com.thoughtworks.xstream.InitializationException#InitializationException(String)} instead */ public InitializationException(String message) { super(message); } } }
./CrossVul/dataset_final_sorted/CWE-78/java/good_4334_1
crossvul-java_data_good_2537_2
package org.codehaus.plexus.util.cli.shell; /* * Copyright The Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * <p> * Class that abstracts the Shell functionality, * with subclases for shells that behave particularly, like * <ul> * <li><code>command.com</code></li> * <li><code>cmd.exe</code></li> * </ul> * </p> * * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a> * @since 1.2 * @version $Id$ */ public class Shell implements Cloneable { private static final char[] DEFAULT_QUOTING_TRIGGER_CHARS = { ' ' }; private String shellCommand; private List<String> shellArgs = new ArrayList<String>(); private boolean quotedArgumentsEnabled = true; private boolean unconditionallyQuote = false; private String executable; private String workingDir; private boolean quotedExecutableEnabled = true; private boolean doubleQuotedArgumentEscaped = false; private boolean singleQuotedArgumentEscaped = false; private boolean doubleQuotedExecutableEscaped = false; private boolean singleQuotedExecutableEscaped = false; private char argQuoteDelimiter = '\"'; private char exeQuoteDelimiter = '\"'; private String argumentEscapePattern = "\\%s"; /** * Toggle unconditional quoting * * @param unconditionallyQuote */ public void setUnconditionalQuoting(boolean unconditionallyQuote) { this.unconditionallyQuote = unconditionallyQuote; } /** * Set the command to execute the shell (eg. COMMAND.COM, /bin/bash,...) * * @param shellCommand */ public void setShellCommand( String shellCommand ) { this.shellCommand = shellCommand; } /** * Get the command to execute the shell * * @return */ public String getShellCommand() { return shellCommand; } /** * Set the shell arguments when calling a command line (not the executable arguments) * (eg. /X /C for CMD.EXE) * * @param shellArgs */ public void setShellArgs( String[] shellArgs ) { this.shellArgs.clear(); this.shellArgs.addAll( Arrays.asList( shellArgs ) ); } /** * Get the shell arguments * * @return */ public String[] getShellArgs() { if ( ( shellArgs == null ) || shellArgs.isEmpty() ) { return null; } else { return (String[]) shellArgs.toArray( new String[shellArgs.size()] ); } } /** * Get the command line for the provided executable and arguments in this shell * * @param executable executable that the shell has to call * @param arguments arguments for the executable, not the shell * @return List with one String object with executable and arguments quoted as needed */ public List<String> getCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } protected String quoteOneItem(String inputString, boolean isExecutable) { char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); return StringUtils.quoteAndEscape( inputString, isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', unconditionallyQuote ); } protected List<String> getRawCommandLine( String executable, String[] arguments ) { List<String> commandLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); if ( executable != null ) { String preamble = getExecutionPreamble(); if ( preamble != null ) { sb.append( preamble ); } if ( isQuotedExecutableEnabled() ) { sb.append( quoteOneItem( getOriginalExecutable(), true ) ); } else { sb.append( getExecutable() ); } } for ( int i = 0; i < arguments.length; i++ ) { if ( sb.length() > 0 ) { sb.append( " " ); } if ( isQuotedArgumentsEnabled() ) { sb.append( quoteOneItem( arguments[i], false ) ); } else { sb.append( arguments[i] ); } } commandLine.add( sb.toString() ); return commandLine; } protected char[] getQuotingTriggerChars() { return DEFAULT_QUOTING_TRIGGER_CHARS; } protected String getExecutionPreamble() { return null; } protected char[] getEscapeChars( boolean includeSingleQuote, boolean includeDoubleQuote ) { StringBuilder buf = new StringBuilder( 2 ); if ( includeSingleQuote ) { buf.append( '\'' ); } if ( includeDoubleQuote ) { buf.append( '\"' ); } char[] result = new char[buf.length()]; buf.getChars( 0, buf.length(), result, 0 ); return result; } protected boolean isDoubleQuotedArgumentEscaped() { return doubleQuotedArgumentEscaped; } protected boolean isSingleQuotedArgumentEscaped() { return singleQuotedArgumentEscaped; } protected boolean isDoubleQuotedExecutableEscaped() { return doubleQuotedExecutableEscaped; } protected boolean isSingleQuotedExecutableEscaped() { return singleQuotedExecutableEscaped; } protected void setArgumentQuoteDelimiter( char argQuoteDelimiter ) { this.argQuoteDelimiter = argQuoteDelimiter; } protected char getArgumentQuoteDelimiter() { return argQuoteDelimiter; } protected void setExecutableQuoteDelimiter( char exeQuoteDelimiter ) { this.exeQuoteDelimiter = exeQuoteDelimiter; } protected char getExecutableQuoteDelimiter() { return exeQuoteDelimiter; } protected void setArgumentEscapePattern(String argumentEscapePattern) { this.argumentEscapePattern = argumentEscapePattern; } protected String getArgumentEscapePattern() { return argumentEscapePattern; } /** * Get the full command line to execute, including shell command, shell arguments, * executable and executable arguments * * @param arguments arguments for the executable, not the shell * @return List of String objects, whose array version is suitable to be used as argument * of Runtime.getRuntime().exec() */ public List<String> getShellCommandLine( String[] arguments ) { List<String> commandLine = new ArrayList<String>(); if ( getShellCommand() != null ) { commandLine.add( getShellCommand() ); } if ( getShellArgs() != null ) { commandLine.addAll( getShellArgsList() ); } commandLine.addAll( getCommandLine( getOriginalExecutable(), arguments ) ); return commandLine; } public List<String> getShellArgsList() { return shellArgs; } public void addShellArg( String arg ) { shellArgs.add( arg ); } public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled ) { this.quotedArgumentsEnabled = quotedArgumentsEnabled; } public boolean isQuotedArgumentsEnabled() { return quotedArgumentsEnabled; } public void setQuotedExecutableEnabled( boolean quotedExecutableEnabled ) { this.quotedExecutableEnabled = quotedExecutableEnabled; } public boolean isQuotedExecutableEnabled() { return quotedExecutableEnabled; } /** * Sets the executable to run. */ public void setExecutable( String executable ) { if ( ( executable == null ) || ( executable.length() == 0 ) ) { return; } this.executable = executable.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); } public String getExecutable() { return executable; } /** * Sets execution directory. */ public void setWorkingDirectory( String path ) { if ( path != null ) { workingDir = path; } } /** * Sets execution directory. */ public void setWorkingDirectory( File workingDir ) { if ( workingDir != null ) { this.workingDir = workingDir.getAbsolutePath(); } } public File getWorkingDirectory() { return workingDir == null ? null : new File( workingDir ); } public String getWorkingDirectoryAsString() { return workingDir; } public void clearArguments() { shellArgs.clear(); } public Object clone() { Shell shell = new Shell(); shell.setExecutable( getExecutable() ); shell.setWorkingDirectory( getWorkingDirectory() ); shell.setShellArgs( getShellArgs() ); return shell; } public String getOriginalExecutable() { return executable; } public List<String> getOriginalCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } protected void setDoubleQuotedArgumentEscaped( boolean doubleQuotedArgumentEscaped ) { this.doubleQuotedArgumentEscaped = doubleQuotedArgumentEscaped; } protected void setDoubleQuotedExecutableEscaped( boolean doubleQuotedExecutableEscaped ) { this.doubleQuotedExecutableEscaped = doubleQuotedExecutableEscaped; } protected void setSingleQuotedArgumentEscaped( boolean singleQuotedArgumentEscaped ) { this.singleQuotedArgumentEscaped = singleQuotedArgumentEscaped; } protected void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped ) { this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } }
./CrossVul/dataset_final_sorted/CWE-78/java/good_2537_2
crossvul-java_data_good_2537_0
package org.codehaus.plexus.util.cli; /* * Copyright The Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************************************** * CruiseControl, a Continuous Integration Toolkit Copyright (c) 2001-2003, ThoughtWorks, Inc. 651 W * Washington Ave. Suite 500 Chicago, IL 60661 USA All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: + Redistributions of source code must retain the * above copyright notice, this list of conditions and the following disclaimer. + Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of ThoughtWorks, Inc., CruiseControl, nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************************************/ /* * ==================================================================== * Copyright 2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.shell.BourneShell; import org.codehaus.plexus.util.cli.shell.CmdShell; import org.codehaus.plexus.util.cli.shell.CommandShell; import org.codehaus.plexus.util.cli.shell.Shell; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * <p/> * Commandline objects help handling command lines specifying processes to * execute. * </p> * <p/> * The class can be used to define a command line as nested elements or as a * helper to define a command line by an application. * </p> * <p/> * <code> * &lt;someelement&gt;<br> * &nbsp;&nbsp;&lt;acommandline executable="/executable/to/run"&gt;<br> * &nbsp;&nbsp;&nbsp;&nbsp;&lt;argument value="argument 1" /&gt;<br> * &nbsp;&nbsp;&nbsp;&nbsp;&lt;argument line="argument_1 argument_2 argument_3" /&gt;<br> * &nbsp;&nbsp;&nbsp;&nbsp;&lt;argument value="argument 4" /&gt;<br> * &nbsp;&nbsp;&lt;/acommandline&gt;<br> * &lt;/someelement&gt;<br> * </code> * </p> * <p/> * The element <code>someelement</code> must provide a method * <code>createAcommandline</code> which returns an instance of this class. * </p> * * @author thomas.haas@softwired-inc.com * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a> */ public class Commandline implements Cloneable { /** * @deprecated Use {@link org.codehaus.plexus.util.Os} class instead. */ protected static final String OS_NAME = "os.name"; /** * @deprecated Use {@link org.codehaus.plexus.util.Os} class instead. */ protected static final String WINDOWS = "Windows"; protected Vector arguments = new Vector(); //protected Vector envVars = new Vector(); // synchronized added to preserve synchronize of Vector class protected Map envVars = Collections.synchronizedMap( new LinkedHashMap() ); private long pid = -1; private Shell shell; /** * @deprecated Use {@link Commandline#setExecutable(String)} instead. */ protected String executable; /** * @deprecated Use {@link Commandline#setWorkingDirectory(File)} or * {@link Commandline#setWorkingDirectory(String)} instead. */ private File workingDir; /** * Create a new command line object. * Shell is autodetected from operating system * * Shell usage is only desirable when generating code for remote execution. * * @param toProcess */ public Commandline( String toProcess, Shell shell ) { this.shell = shell; String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( "Error translating Commandline." ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } /** * Create a new command line object. * Shell is autodetected from operating system * * Shell usage is only desirable when generating code for remote execution. */ public Commandline( Shell shell ) { this.shell = shell; } /** * Create a new command line object, given a command following POSIX sh quoting rules * * @param toProcess */ public Commandline( String toProcess ) { setDefaultShell(); String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( "Error translating Commandline." ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } /** * Create a new command line object. */ public Commandline() { setDefaultShell(); } public long getPid() { if ( pid == -1 ) { pid = Long.parseLong( String.valueOf( System.currentTimeMillis() ) ); } return pid; } public void setPid( long pid ) { this.pid = pid; } /** * Class to keep track of the position of an Argument. */ // <p>This class is there to support the srcfile and targetfile // elements of &lt;execon&gt; and &lt;transform&gt; - don't know // whether there might be additional use cases.</p> --SB public class Marker { private int position; private int realPos = -1; Marker( int position ) { this.position = position; } /** * Return the number of arguments that preceeded this marker. * <p/> * <p>The name of the executable - if set - is counted as the * very first argument.</p> */ public int getPosition() { if ( realPos == -1 ) { realPos = ( getLiteralExecutable() == null ? 0 : 1 ); for ( int i = 0; i < position; i++ ) { Arg arg = (Arg) arguments.elementAt( i ); realPos += arg.getParts().length; } } return realPos; } } /** * <p>Sets the shell or command-line interpretor for the detected operating system, * and the shell arguments.</p> */ private void setDefaultShell() { //If this is windows set the shell to command.com or cmd.exe with correct arguments. if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { if ( Os.isFamily( Os.FAMILY_WIN9X ) ) { setShell( new CommandShell() ); } else { setShell( new CmdShell() ); } } else { setShell( new BourneShell() ); } } /** * Creates an argument object. * <p/> * <p>Each commandline object has at most one instance of the * argument class. This method calls * <code>this.createArgument(false)</code>.</p> * * @return the argument object. * @see #createArgument(boolean) * @deprecated Use {@link Commandline#createArg()} instead */ public Argument createArgument() { return this.createArgument( false ); } /** * Creates an argument object and adds it to our list of args. * <p/> * <p>Each commandline object has at most one instance of the * argument class.</p> * * @param insertAtStart if true, the argument is inserted at the * beginning of the list of args, otherwise it is appended. * @deprecated Use {@link Commandline#createArg(boolean)} instead */ public Argument createArgument( boolean insertAtStart ) { Argument argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } /** * Creates an argument object. * <p/> * <p>Each commandline object has at most one instance of the * argument class. This method calls * <code>this.createArgument(false)</code>.</p> * * @return the argument object. * @see #createArgument(boolean) */ public Arg createArg() { return this.createArg( false ); } /** * Creates an argument object and adds it to our list of args. * <p/> * <p>Each commandline object has at most one instance of the * argument class.</p> * * @param insertAtStart if true, the argument is inserted at the * beginning of the list of args, otherwise it is appended. */ public Arg createArg( boolean insertAtStart ) { Arg argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } /** * Adds an argument object to our list of args. * * @return the argument object. * @see #addArg(Arg,boolean) */ public void addArg( Arg argument ) { this.addArg( argument, false ); } /** * Adds an argument object to our list of args. * * @param insertAtStart if true, the argument is inserted at the * beginning of the list of args, otherwise it is appended. */ public void addArg( Arg argument, boolean insertAtStart ) { if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } } /** * Sets the executable to run. */ public void setExecutable( String executable ) { shell.setExecutable( executable ); this.executable = executable; } /** * @return Executable to be run, as a literal string (no shell quoting/munging) */ public String getLiteralExecutable() { return executable; } /** * Return an executable name, quoted for shell use. * * Shell usage is only desirable when generating code for remote execution. * * @return Executable to be run, quoted for shell interpretation */ public String getExecutable() { String exec = shell.getExecutable(); if ( exec == null ) { exec = executable; } return exec; } public void addArguments( String[] line ) { for ( int i = 0; i < line.length; i++ ) { createArgument().setValue( line[i] ); } } /** * Add an environment variable */ public void addEnvironment( String name, String value ) { //envVars.add( name + "=" + value ); envVars.put( name, value ); } /** * Add system environment variables */ public void addSystemEnvironment() throws Exception { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); if ( !envVars.containsKey( key ) ) { addEnvironment( key, systemEnvVars.getProperty( key ) ); } } } /** * Return the list of environment variables */ public String[] getEnvironmentVariables() throws CommandLineException { try { addSystemEnvironment(); } catch ( Exception e ) { throw new CommandLineException( "Error setting up environmental variables", e ); } String[] environmentVars = new String[envVars.size()]; int i = 0; for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); ) { String name = (String) iterator.next(); String value = (String) envVars.get( name ); environmentVars[i] = name + "=" + value; i++; } return environmentVars; } /** * Returns the executable and all defined arguments. */ public String[] getCommandline() { final String[] args = getArguments(); String executable = getLiteralExecutable(); if ( executable == null ) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; System.arraycopy( args, 0, result, 1, args.length ); return result; } /** * Returns the shell, executable and all defined arguments. * * Shell usage is only desirable when generating code for remote execution. */ public String[] getShellCommandline() { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); return (String[]) getShell().getShellCommandLine( getArguments() ).toArray( new String[0] ); } /** * Returns all arguments defined by <code>addLine</code>, * <code>addValue</code> or the argument object. */ public String[] getArguments() { Vector result = new Vector( arguments.size() * 2 ); for ( int i = 0; i < arguments.size(); i++ ) { Argument arg = (Argument) arguments.elementAt( i ); String[] s = arg.getParts(); if ( s != null ) { for ( int j = 0; j < s.length; j++ ) { result.addElement( s[j] ); } } } String[] res = new String[result.size()]; result.copyInto( res ); return res; } public String toString() { return StringUtils.join( getShellCommandline(), " " ); } public int size() { return getCommandline().length; } public Object clone() { Commandline c = new Commandline( (Shell) shell.clone() ); c.executable = executable; c.workingDir = workingDir; c.addArguments( getArguments() ); return c; } /** * Clear out the whole command line. */ public void clear() { executable = null; workingDir = null; shell.setExecutable( null ); shell.clearArguments(); arguments.removeAllElements(); } /** * Clear out the arguments but leave the executable in place for another operation. */ public void clearArgs() { arguments.removeAllElements(); } /** * Return a marker. * <p/> * <p>This marker can be used to locate a position on the * commandline - to insert something for example - when all * parameters have been set.</p> */ public Marker createMarker() { return new Marker( arguments.size() ); } /** * Sets execution directory. */ public void setWorkingDirectory( String path ) { shell.setWorkingDirectory( path ); workingDir = new File( path ); } /** * Sets execution directory. */ public void setWorkingDirectory( File workingDirectory ) { shell.setWorkingDirectory( workingDirectory ); workingDir = workingDirectory; } public File getWorkingDirectory() { File workDir = shell.getWorkingDirectory(); if ( workDir == null ) { workDir = workingDir; } return workDir; } /** * Executes the command. */ public Process execute() throws CommandLineException { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); Process process; //addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" ); String[] environment = getEnvironmentVariables(); File workingDir = shell.getWorkingDirectory(); try { if ( workingDir == null ) { process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); } else { if ( !workingDir.exists() ) { throw new CommandLineException( "Working directory \"" + workingDir.getPath() + "\" does not exist!" ); } else if ( !workingDir.isDirectory() ) { throw new CommandLineException( "Path \"" + workingDir.getPath() + "\" does not specify a directory." ); } process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); } } catch ( IOException ex ) { throw new CommandLineException( "Error while executing process.", ex ); } return process; } /** * @deprecated Remove once backward compat with plexus-utils <= 1.4 is no longer a consideration */ private void verifyShellState() { if ( shell.getWorkingDirectory() == null ) { shell.setWorkingDirectory( workingDir ); } if ( shell.getOriginalExecutable() == null ) { shell.setExecutable( executable ); } } public Properties getSystemEnvVars() throws Exception { return CommandLineUtils.getSystemEnvVars(); } /** * Allows to set the shell to be used in this command line. * * Shell usage is only desirable when generating code for remote execution. * * @param shell * @since 1.2 */ public void setShell( Shell shell ) { this.shell = shell; } /** * Get the shell to be used in this command line. * * Shell usage is only desirable when generating code for remote execution. * @since 1.2 */ public Shell getShell() { return shell; } /** * @deprecated Use {@link CommandLineUtils#translateCommandline(String)} instead. */ public static String[] translateCommandline( String toProcess ) throws Exception { return CommandLineUtils.translateCommandline( toProcess ); } /** * @deprecated Use {@link CommandLineUtils#quote(String)} instead. */ public static String quoteArgument( String argument ) throws CommandLineException { return CommandLineUtils.quote( argument ); } /** * @deprecated Use {@link CommandLineUtils#toString(String[])} instead. */ public static String toString( String[] line ) { return CommandLineUtils.toString( line ); } public static class Argument implements Arg { private String[] parts; /* (non-Javadoc) * @see org.codehaus.plexus.util.cli.Argumnt#setValue(java.lang.String) */ public void setValue( String value ) { if ( value != null ) { parts = new String[] { value }; } } /* (non-Javadoc) * @see org.codehaus.plexus.util.cli.Argumnt#setLine(java.lang.String) */ public void setLine( String line ) { if ( line == null ) { return; } try { parts = CommandLineUtils.translateCommandline( line ); } catch ( Exception e ) { System.err.println( "Error translating Commandline." ); } } /* (non-Javadoc) * @see org.codehaus.plexus.util.cli.Argumnt#setFile(java.io.File) */ public void setFile( File value ) { parts = new String[] { value.getAbsolutePath() }; } /* (non-Javadoc) * @see org.codehaus.plexus.util.cli.Argumnt#getParts() */ public String[] getParts() { return parts; } } }
./CrossVul/dataset_final_sorted/CWE-78/java/good_2537_0
crossvul-java_data_good_2537_1
package org.codehaus.plexus.util.cli.shell; /* * Copyright The Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.codehaus.plexus.util.Os; import java.util.ArrayList; import java.util.List; /** * @author Jason van Zyl * @version $Id$ */ public class BourneShell extends Shell { public BourneShell() { this(false); } public BourneShell( boolean isLoginShell ) { setUnconditionalQuoting( true ); setShellCommand( "/bin/sh" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\'' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern("'\\%s'"); if ( isLoginShell ) { addShellArg( "-l" ); } } /** {@inheritDoc} */ public String getExecutable() { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { return super.getExecutable(); } return quoteOneItem( super.getOriginalExecutable(), true ); } public List<String> getShellArgsList() { List<String> shellArgs = new ArrayList<String>(); List<String> existingShellArgs = super.getShellArgsList(); if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() ) { shellArgs.addAll( existingShellArgs ); } shellArgs.add( "-c" ); return shellArgs; } public String[] getShellArgs() { String[] shellArgs = super.getShellArgs(); if ( shellArgs == null ) { shellArgs = new String[0]; } if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( "-c" ) ) { String[] newArgs = new String[shellArgs.length + 1]; System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length ); newArgs[shellArgs.length] = "-c"; shellArgs = newArgs; } return shellArgs; } protected String getExecutionPreamble() { if ( getWorkingDirectoryAsString() == null ) { return null; } String dir = getWorkingDirectoryAsString(); StringBuilder sb = new StringBuilder(); sb.append( "cd " ); sb.append( quoteOneItem( dir, false ) ); sb.append( " && " ); return sb.toString(); } /** * <p>Unify quotes in a path for the Bourne Shell.</p> * * <pre> * BourneShell.quoteOneItem(null) = null * BourneShell.quoteOneItem("") = '' * BourneShell.quoteOneItem("/test/quotedpath'abc") = '/test/quotedpath'"'"'abc' * BourneShell.quoteOneItem("/test/quoted path'abc") = '/test/quoted pat'"'"'habc' * BourneShell.quoteOneItem("/test/quotedpath\"abc") = '/test/quotedpath"abc' * BourneShell.quoteOneItem("/test/quoted path\"abc") = '/test/quoted path"abc' * BourneShell.quoteOneItem("/test/quotedpath\"'abc") = '/test/quotedpath"'"'"'abc' * BourneShell.quoteOneItem("/test/quoted path\"'abc") = '/test/quoted path"'"'"'abc' * </pre> * * @param path not null path. * @return the path unified correctly for the Bourne shell. */ protected String quoteOneItem( String path, boolean isExecutable ) { if ( path == null ) { return null; } StringBuilder sb = new StringBuilder(); sb.append( "'" ); sb.append( path.replace( "'", "'\"'\"'" ) ); sb.append( "'" ); return sb.toString(); } }
./CrossVul/dataset_final_sorted/CWE-78/java/good_2537_1
crossvul-java_data_bad_2537_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-78/java/bad_2537_0
crossvul-java_data_bad_873_0
package org.dynmap.servlet; import org.dynmap.DynmapCore; import org.dynmap.DynmapWorld; import org.dynmap.MapType.ImageEncoding; import org.dynmap.PlayerFaces; import org.dynmap.storage.MapStorage; import org.dynmap.storage.MapStorageTile; import org.dynmap.storage.MapStorageTile.TileRead; import org.dynmap.utils.BufferInputStream; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.OutputStream; public class MapStorageResourceHandler extends AbstractHandler { private DynmapCore core; private byte[] blankpng; private long blankpnghash = 0x12345678; public MapStorageResourceHandler() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedImage blank = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); try { ImageIO.write(blank, "png", baos); blankpng = baos.toByteArray(); } catch (IOException e) { } } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = baseRequest.getPathInfo(); int soff = 0, eoff; // We're handling this request baseRequest.setHandled(true); if (path.charAt(0) == '/') soff = 1; eoff = path.indexOf('/', soff); if (soff < 0) { response.sendError(HttpStatus.NOT_FOUND_404); return; } String world = path.substring(soff, eoff); String uri = path.substring(eoff+1); // If faces directory, handle faces if (world.equals("faces")) { handleFace(response, uri); return; } // If markers directory, handle markers if (world.equals("_markers_")) { handleMarkers(response, uri); return; } DynmapWorld w = null; if (core.mapManager != null) { w = core.mapManager.getWorld(world); } // If world not found quit if (w == null) { response.setContentType("image/png"); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } MapStorage store = w.getMapStorage(); // Get storage handler // Get tile reference, based on URI and world MapStorageTile tile = store.getTile(w, uri); if (tile == null) { response.setContentType("image/png"); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } // Read tile TileRead tr = null; if (tile.getReadLock(5000)) { tr = tile.read(); tile.releaseReadLock(); } response.setHeader("Cache-Control", "max-age=0,must-revalidate"); String etag; if (tr == null) { etag = "\"" + blankpnghash + "\""; } else { etag = "\"" + tr.hashCode + "\""; } response.setHeader("ETag", etag); String ifnullmatch = request.getHeader("If-None-Match"); if ((ifnullmatch != null) && ifnullmatch.equals(etag)) { response.sendError(HttpStatus.NOT_MODIFIED_304); return; } if (tr == null) { response.setContentType("image/png"); response.setIntHeader("Content-Length", blankpng.length); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } // Got tile, package up for response response.setDateHeader("Last-Modified", tr.lastModified); response.setIntHeader("Content-Length", tr.image.length()); if (tr.format == ImageEncoding.PNG) { response.setContentType("image/png"); } else { response.setContentType("image/jpeg"); } ServletOutputStream out = response.getOutputStream(); out.write(tr.image.buffer(), 0, tr.image.length()); out.flush(); } private void handleFace(HttpServletResponse response, String uri) throws IOException, ServletException { String[] suri = uri.split("[/\\.]"); if (suri.length < 3) { // 3 parts : face ID, player name, png response.sendError(HttpStatus.NOT_FOUND_404); return; } // Find type PlayerFaces.FaceType ft = PlayerFaces.FaceType.byID(suri[0]); if (ft == null) { response.sendError(HttpStatus.NOT_FOUND_404); return; } BufferInputStream bis = null; if (core.playerfacemgr != null) { bis = core.playerfacemgr.storage.getPlayerFaceImage(suri[1], ft); } if (bis == null) { response.sendError(HttpStatus.NOT_FOUND_404); return; } // Got image, package up for response response.setIntHeader("Content-Length", bis.length()); response.setContentType("image/png"); ServletOutputStream out = response.getOutputStream(); out.write(bis.buffer(), 0, bis.length()); out.flush(); } private void handleMarkers(HttpServletResponse response, String uri) throws IOException, ServletException { String[] suri = uri.split("/"); // If json file in last part if ((suri.length == 1) && suri[0].startsWith("marker_") && suri[0].endsWith(".json")) { String content = core.getDefaultMapStorage().getMarkerFile(suri[0].substring(7, suri[0].length() - 5)); response.setContentType("application/json"); PrintWriter pw = response.getWriter(); pw.print(content); pw.flush(); return; } // If png, make marker ID if (suri[suri.length-1].endsWith(".png")) { BufferInputStream bis = core.getDefaultMapStorage().getMarkerImage(uri.substring(0, uri.length()-4)); // Got image, package up for response response.setIntHeader("Content-Length", bis.length()); response.setContentType("image/png"); ServletOutputStream out = response.getOutputStream(); out.write(bis.buffer(), 0, bis.length()); out.flush(); return; } response.sendError(HttpStatus.NOT_FOUND_404); } public void setCore(DynmapCore core) { this.core = core; } }
./CrossVul/dataset_final_sorted/CWE-284/java/bad_873_0
crossvul-java_data_good_873_0
package org.dynmap.servlet; import org.dynmap.DynmapCore; import org.dynmap.DynmapWorld; import org.dynmap.MapType.ImageEncoding; import org.dynmap.PlayerFaces; import org.dynmap.storage.MapStorage; import org.dynmap.storage.MapStorageTile; import org.dynmap.storage.MapStorageTile.TileRead; import org.dynmap.utils.BufferInputStream; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.OutputStream; public class MapStorageResourceHandler extends AbstractHandler { private DynmapCore core; private byte[] blankpng; private long blankpnghash = 0x12345678; public MapStorageResourceHandler() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedImage blank = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); try { ImageIO.write(blank, "png", baos); blankpng = baos.toByteArray(); } catch (IOException e) { } } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = baseRequest.getPathInfo(); int soff = 0, eoff; // We're handling this request baseRequest.setHandled(true); if(core.getLoginRequired() && request.getSession(true).getAttribute(LoginServlet.USERID_ATTRIB) == null){ response.sendError(HttpStatus.UNAUTHORIZED_401); return; } if (path.charAt(0) == '/') soff = 1; eoff = path.indexOf('/', soff); if (soff < 0) { response.sendError(HttpStatus.NOT_FOUND_404); return; } String world = path.substring(soff, eoff); String uri = path.substring(eoff+1); // If faces directory, handle faces if (world.equals("faces")) { handleFace(response, uri); return; } // If markers directory, handle markers if (world.equals("_markers_")) { handleMarkers(response, uri); return; } DynmapWorld w = null; if (core.mapManager != null) { w = core.mapManager.getWorld(world); } // If world not found quit if (w == null) { response.setContentType("image/png"); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } MapStorage store = w.getMapStorage(); // Get storage handler // Get tile reference, based on URI and world MapStorageTile tile = store.getTile(w, uri); if (tile == null) { response.setContentType("image/png"); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } // Read tile TileRead tr = null; if (tile.getReadLock(5000)) { tr = tile.read(); tile.releaseReadLock(); } response.setHeader("Cache-Control", "max-age=0,must-revalidate"); String etag; if (tr == null) { etag = "\"" + blankpnghash + "\""; } else { etag = "\"" + tr.hashCode + "\""; } response.setHeader("ETag", etag); String ifnullmatch = request.getHeader("If-None-Match"); if ((ifnullmatch != null) && ifnullmatch.equals(etag)) { response.sendError(HttpStatus.NOT_MODIFIED_304); return; } if (tr == null) { response.setContentType("image/png"); response.setIntHeader("Content-Length", blankpng.length); OutputStream os = response.getOutputStream(); os.write(blankpng); return; } // Got tile, package up for response response.setDateHeader("Last-Modified", tr.lastModified); response.setIntHeader("Content-Length", tr.image.length()); if (tr.format == ImageEncoding.PNG) { response.setContentType("image/png"); } else { response.setContentType("image/jpeg"); } ServletOutputStream out = response.getOutputStream(); out.write(tr.image.buffer(), 0, tr.image.length()); out.flush(); } private void handleFace(HttpServletResponse response, String uri) throws IOException, ServletException { String[] suri = uri.split("[/\\.]"); if (suri.length < 3) { // 3 parts : face ID, player name, png response.sendError(HttpStatus.NOT_FOUND_404); return; } // Find type PlayerFaces.FaceType ft = PlayerFaces.FaceType.byID(suri[0]); if (ft == null) { response.sendError(HttpStatus.NOT_FOUND_404); return; } BufferInputStream bis = null; if (core.playerfacemgr != null) { bis = core.playerfacemgr.storage.getPlayerFaceImage(suri[1], ft); } if (bis == null) { response.sendError(HttpStatus.NOT_FOUND_404); return; } // Got image, package up for response response.setIntHeader("Content-Length", bis.length()); response.setContentType("image/png"); ServletOutputStream out = response.getOutputStream(); out.write(bis.buffer(), 0, bis.length()); out.flush(); } private void handleMarkers(HttpServletResponse response, String uri) throws IOException, ServletException { String[] suri = uri.split("/"); // If json file in last part if ((suri.length == 1) && suri[0].startsWith("marker_") && suri[0].endsWith(".json")) { String content = core.getDefaultMapStorage().getMarkerFile(suri[0].substring(7, suri[0].length() - 5)); response.setContentType("application/json"); PrintWriter pw = response.getWriter(); pw.print(content); pw.flush(); return; } // If png, make marker ID if (suri[suri.length-1].endsWith(".png")) { BufferInputStream bis = core.getDefaultMapStorage().getMarkerImage(uri.substring(0, uri.length()-4)); // Got image, package up for response response.setIntHeader("Content-Length", bis.length()); response.setContentType("image/png"); ServletOutputStream out = response.getOutputStream(); out.write(bis.buffer(), 0, bis.length()); out.flush(); return; } response.sendError(HttpStatus.NOT_FOUND_404); } public void setCore(DynmapCore core) { this.core = core; } }
./CrossVul/dataset_final_sorted/CWE-284/java/good_873_0
crossvul-java_data_good_4759_0
package org.bouncycastle.asn1; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.util.Arrays; /** * Class representing the ASN.1 ENUMERATED type. */ public class ASN1Enumerated extends ASN1Primitive { private final byte[] bytes; /** * return an enumerated from the passed in object * * @param obj an ASN1Enumerated or an object that can be converted into one. * @exception IllegalArgumentException if the object cannot be converted. * @return an ASN1Enumerated instance, or null. */ public static ASN1Enumerated getInstance( Object obj) { if (obj == null || obj instanceof ASN1Enumerated) { return (ASN1Enumerated)obj; } if (obj instanceof byte[]) { try { return (ASN1Enumerated)fromByteArray((byte[])obj); } catch (Exception e) { throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); } } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an Enumerated from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return an ASN1Enumerated instance, or null. */ public static ASN1Enumerated getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof ASN1Enumerated) { return getInstance(o); } else { return fromOctetString(((ASN1OctetString)o).getOctets()); } } /** * Constructor from int. * * @param value the value of this enumerated. */ public ASN1Enumerated( int value) { bytes = BigInteger.valueOf(value).toByteArray(); } /** * Constructor from BigInteger * * @param value the value of this enumerated. */ public ASN1Enumerated( BigInteger value) { bytes = value.toByteArray(); } /** * Constructor from encoded BigInteger. * * @param bytes the value of this enumerated as an encoded BigInteger (signed). */ public ASN1Enumerated( byte[] bytes) { if (bytes.length > 1) { if (bytes[0] == 0 && (bytes[1] & 0x80) == 0) { throw new IllegalArgumentException("malformed enumerated"); } if (bytes[0] == (byte)0xff && (bytes[1] & 0x80) != 0) { throw new IllegalArgumentException("malformed enumerated"); } } this.bytes = Arrays.clone(bytes); } public BigInteger getValue() { return new BigInteger(bytes); } boolean isConstructed() { return false; } int encodedLength() { return 1 + StreamUtil.calculateBodyLength(bytes.length) + bytes.length; } void encode( ASN1OutputStream out) throws IOException { out.writeEncoded(BERTags.ENUMERATED, bytes); } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof ASN1Enumerated)) { return false; } ASN1Enumerated other = (ASN1Enumerated)o; return Arrays.areEqual(this.bytes, other.bytes); } public int hashCode() { return Arrays.hashCode(bytes); } private static ASN1Enumerated[] cache = new ASN1Enumerated[12]; static ASN1Enumerated fromOctetString(byte[] enc) { if (enc.length > 1) { return new ASN1Enumerated(enc); } if (enc.length == 0) { throw new IllegalArgumentException("ENUMERATED has zero length"); } int value = enc[0] & 0xff; if (value >= cache.length) { return new ASN1Enumerated(Arrays.clone(enc)); } ASN1Enumerated possibleMatch = cache[value]; if (possibleMatch == null) { possibleMatch = cache[value] = new ASN1Enumerated(Arrays.clone(enc)); } return possibleMatch; } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_0
crossvul-java_data_bad_4759_0
package org.bouncycastle.asn1; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.util.Arrays; /** * Class representing the ASN.1 ENUMERATED type. */ public class ASN1Enumerated extends ASN1Primitive { private final byte[] bytes; /** * return an enumerated from the passed in object * * @param obj an ASN1Enumerated or an object that can be converted into one. * @exception IllegalArgumentException if the object cannot be converted. * @return an ASN1Enumerated instance, or null. */ public static ASN1Enumerated getInstance( Object obj) { if (obj == null || obj instanceof ASN1Enumerated) { return (ASN1Enumerated)obj; } if (obj instanceof byte[]) { try { return (ASN1Enumerated)fromByteArray((byte[])obj); } catch (Exception e) { throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); } } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an Enumerated from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return an ASN1Enumerated instance, or null. */ public static ASN1Enumerated getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof ASN1Enumerated) { return getInstance(o); } else { return fromOctetString(((ASN1OctetString)o).getOctets()); } } /** * Constructor from int. * * @param value the value of this enumerated. */ public ASN1Enumerated( int value) { bytes = BigInteger.valueOf(value).toByteArray(); } /** * Constructor from BigInteger * * @param value the value of this enumerated. */ public ASN1Enumerated( BigInteger value) { bytes = value.toByteArray(); } /** * Constructor from encoded BigInteger. * * @param bytes the value of this enumerated as an encoded BigInteger (signed). */ public ASN1Enumerated( byte[] bytes) { this.bytes = Arrays.clone(bytes); } public BigInteger getValue() { return new BigInteger(bytes); } boolean isConstructed() { return false; } int encodedLength() { return 1 + StreamUtil.calculateBodyLength(bytes.length) + bytes.length; } void encode( ASN1OutputStream out) throws IOException { out.writeEncoded(BERTags.ENUMERATED, bytes); } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof ASN1Enumerated)) { return false; } ASN1Enumerated other = (ASN1Enumerated)o; return Arrays.areEqual(this.bytes, other.bytes); } public int hashCode() { return Arrays.hashCode(bytes); } private static ASN1Enumerated[] cache = new ASN1Enumerated[12]; static ASN1Enumerated fromOctetString(byte[] enc) { if (enc.length > 1) { return new ASN1Enumerated(enc); } if (enc.length == 0) { throw new IllegalArgumentException("ENUMERATED has zero length"); } int value = enc[0] & 0xff; if (value >= cache.length) { return new ASN1Enumerated(Arrays.clone(enc)); } ASN1Enumerated possibleMatch = cache[value]; if (possibleMatch == null) { possibleMatch = cache[value] = new ASN1Enumerated(Arrays.clone(enc)); } return possibleMatch; } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_0
crossvul-java_data_good_4759_2
package org.bouncycastle.asn1.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.BERSequence; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.misc.CAST5CBCParameters; import org.bouncycastle.asn1.misc.IDEACBCPar; import org.bouncycastle.asn1.misc.NetscapeCertType; import org.bouncycastle.asn1.misc.NetscapeRevocationURL; import org.bouncycastle.asn1.misc.VerisignCzagExtension; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; public class MiscTest extends SimpleTest { private boolean isSameAs( byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public void shouldFailOnExtraData() throws Exception { // basic construction DERBitString s1 = new DERBitString(new byte[0], 0); ASN1Primitive.fromByteArray(s1.getEncoded()); ASN1Primitive.fromByteArray(new BERSequence(s1).getEncoded()); try { ASN1Primitive obj = ASN1Primitive.fromByteArray(Arrays.concatenate(s1.getEncoded(), new byte[1])); fail("no exception"); } catch (IOException e) { if (!"Extra data detected in stream".equals(e.getMessage())) { fail("wrong exception"); } } } public void derIntegerTest() throws Exception { try { new ASN1Integer(new byte[] { 0, 0, 0, 1}); } catch (IllegalArgumentException e) { isTrue("wrong exc", "malformed integer".equals(e.getMessage())); } try { new ASN1Integer(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); } catch (IllegalArgumentException e) { isTrue("wrong exc", "malformed integer".equals(e.getMessage())); } try { new ASN1Enumerated(new byte[] { 0, 0, 0, 1}); } catch (IllegalArgumentException e) { isTrue("wrong exc", "malformed enumerated".equals(e.getMessage())); } try { new ASN1Enumerated(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); } catch (IllegalArgumentException e) { isTrue("wrong exc", "malformed enumerated".equals(e.getMessage())); } } public void performTest() throws Exception { byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 }; ASN1Encodable[] values = { new CAST5CBCParameters(testIv, 128), new NetscapeCertType(NetscapeCertType.smime), new VerisignCzagExtension(new DERIA5String("hello")), new IDEACBCPar(testIv), new NetscapeRevocationURL(new DERIA5String("http://test")) }; byte[] data = Base64.decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA=="); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } ASN1Primitive[] readValues = new ASN1Primitive[values.length]; if (!isSameAs(bOut.toByteArray(), data)) { fail("Failed data check"); } ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { ASN1Primitive o = aIn.readObject(); if (!values[i].equals(o)) { fail("Failed equality test for " + o); } if (o.hashCode() != values[i].hashCode()) { fail("Failed hashCode test for " + o); } } shouldFailOnExtraData(); derIntegerTest(); } public String getName() { return "Misc"; } public static void main( String[] args) { runTest(new MiscTest()); } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_2
crossvul-java_data_bad_4759_5
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_5
crossvul-java_data_bad_4754_1
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4754_1
crossvul-java_data_bad_4754_0
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.SignatureSpi; import java.security.interfaces.DSAKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; public class DSASigner extends SignatureSpi implements PKCSObjectIdentifiers, X509ObjectIdentifiers { private Digest digest; private DSA signer; private SecureRandom random; protected DSASigner( Digest digest, DSA signer) { this.digest = digest; this.signer = signer; } protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey, SecureRandom random) throws InvalidKeyException { this.random = random; engineInitSign(privateKey); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePrivateKeyParameter(privateKey); if (random != null) { param = new ParametersWithRandom(param, random); } digest.reset(); signer.init(true, param); } protected void engineUpdate( byte b) throws SignatureException { digest.update(b); } protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { digest.update(b, off, len); } protected byte[] engineSign() throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { BigInteger[] sig = signer.generateSignature(hash); return derEncode(sig[0], sig[1]); } catch (Exception e) { throw new SignatureException(e.toString()); } } protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); } protected void engineSetParameter( AlgorithmParameterSpec params) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> */ protected void engineSetParameter( String param, Object value) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated */ protected Object engineGetParameter( String param) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } private byte[] derEncode( BigInteger r, BigInteger s) throws IOException { ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; return new DERSequence(rs).getEncoded(ASN1Encoding.DER); } private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); return new BigInteger[]{ ((ASN1Integer)s.getObjectAt(0)).getValue(), ((ASN1Integer)s.getObjectAt(1)).getValue() }; } static public class stdDSA extends DSASigner { public stdDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA extends DSASigner { public detDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA1Digest()))); } } static public class dsa224 extends DSASigner { public dsa224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA224 extends DSASigner { public detDSA224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA224Digest()))); } } static public class dsa256 extends DSASigner { public dsa256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA256 extends DSASigner { public detDSA256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA256Digest()))); } } static public class dsa384 extends DSASigner { public dsa384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA384 extends DSASigner { public detDSA384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA384Digest()))); } } static public class dsa512 extends DSASigner { public dsa512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA512 extends DSASigner { public detDSA512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA512Digest()))); } } static public class dsaSha3_224 extends DSASigner { public dsaSha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_224 extends DSASigner { public detDSASha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(224)))); } } static public class dsaSha3_256 extends DSASigner { public dsaSha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_256 extends DSASigner { public detDSASha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(256)))); } } static public class dsaSha3_384 extends DSASigner { public dsaSha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_384 extends DSASigner { public detDSASha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(384)))); } } static public class dsaSha3_512 extends DSASigner { public dsaSha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_512 extends DSASigner { public detDSASha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(512)))); } } static public class noneDSA extends DSASigner { public noneDSA() { super(new NullDigest(), new org.bouncycastle.crypto.signers.DSASigner()); } } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4754_0
crossvul-java_data_good_4759_5
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100", "303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_5
crossvul-java_data_good_4759_3
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.SignatureSpi; import java.security.spec.AlgorithmParameterSpec; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; import org.bouncycastle.util.Arrays; public class DSASigner extends SignatureSpi implements PKCSObjectIdentifiers, X509ObjectIdentifiers { private Digest digest; private DSA signer; private SecureRandom random; protected DSASigner( Digest digest, DSA signer) { this.digest = digest; this.signer = signer; } protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey, SecureRandom random) throws InvalidKeyException { this.random = random; engineInitSign(privateKey); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePrivateKeyParameter(privateKey); if (random != null) { param = new ParametersWithRandom(param, random); } digest.reset(); signer.init(true, param); } protected void engineUpdate( byte b) throws SignatureException { digest.update(b); } protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { digest.update(b, off, len); } protected byte[] engineSign() throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { BigInteger[] sig = signer.generateSignature(hash); return derEncode(sig[0], sig[1]); } catch (Exception e) { throw new SignatureException(e.toString()); } } protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); } protected void engineSetParameter( AlgorithmParameterSpec params) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> */ protected void engineSetParameter( String param, Object value) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated */ protected Object engineGetParameter( String param) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } private byte[] derEncode( BigInteger r, BigInteger s) throws IOException { ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; return new DERSequence(rs).getEncoded(ASN1Encoding.DER); } private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER))) { throw new IOException("malformed signature"); } return new BigInteger[]{ ((ASN1Integer)s.getObjectAt(0)).getValue(), ((ASN1Integer)s.getObjectAt(1)).getValue() }; } static public class stdDSA extends DSASigner { public stdDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA extends DSASigner { public detDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA1Digest()))); } } static public class dsa224 extends DSASigner { public dsa224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA224 extends DSASigner { public detDSA224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA224Digest()))); } } static public class dsa256 extends DSASigner { public dsa256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA256 extends DSASigner { public detDSA256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA256Digest()))); } } static public class dsa384 extends DSASigner { public dsa384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA384 extends DSASigner { public detDSA384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA384Digest()))); } } static public class dsa512 extends DSASigner { public dsa512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA512 extends DSASigner { public detDSA512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA512Digest()))); } } static public class dsaSha3_224 extends DSASigner { public dsaSha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_224 extends DSASigner { public detDSASha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(224)))); } } static public class dsaSha3_256 extends DSASigner { public dsaSha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_256 extends DSASigner { public detDSASha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(256)))); } } static public class dsaSha3_384 extends DSASigner { public dsaSha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_384 extends DSASigner { public detDSASha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(384)))); } } static public class dsaSha3_512 extends DSASigner { public dsaSha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_512 extends DSASigner { public detDSASha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(512)))); } } static public class noneDSA extends DSASigner { public noneDSA() { super(new NullDigest(), new org.bouncycastle.crypto.signers.DSASigner()); } } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_3
crossvul-java_data_bad_4759_1
package org.bouncycastle.asn1; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.util.Arrays; /** * Class representing the ASN.1 INTEGER type. */ public class ASN1Integer extends ASN1Primitive { private final byte[] bytes; /** * return an integer from the passed in object * * @param obj an ASN1Integer or an object that can be converted into one. * @throws IllegalArgumentException if the object cannot be converted. * @return an ASN1Integer instance. */ public static ASN1Integer getInstance( Object obj) { if (obj == null || obj instanceof ASN1Integer) { return (ASN1Integer)obj; } if (obj instanceof byte[]) { try { return (ASN1Integer)fromByteArray((byte[])obj); } catch (Exception e) { throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); } } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an Integer from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @throws IllegalArgumentException if the tagged object cannot * be converted. * @return an ASN1Integer instance. */ public static ASN1Integer getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof ASN1Integer) { return getInstance(o); } else { return new ASN1Integer(ASN1OctetString.getInstance(obj.getObject()).getOctets()); } } public ASN1Integer( long value) { bytes = BigInteger.valueOf(value).toByteArray(); } public ASN1Integer( BigInteger value) { bytes = value.toByteArray(); } public ASN1Integer( byte[] bytes) { this(bytes, true); } ASN1Integer(byte[] bytes, boolean clone) { this.bytes = (clone) ? Arrays.clone(bytes) : bytes; } public BigInteger getValue() { return new BigInteger(bytes); } /** * in some cases positive values get crammed into a space, * that's not quite big enough... * @return the BigInteger that results from treating this ASN.1 INTEGER as unsigned. */ public BigInteger getPositiveValue() { return new BigInteger(1, bytes); } boolean isConstructed() { return false; } int encodedLength() { return 1 + StreamUtil.calculateBodyLength(bytes.length) + bytes.length; } void encode( ASN1OutputStream out) throws IOException { out.writeEncoded(BERTags.INTEGER, bytes); } public int hashCode() { int value = 0; for (int i = 0; i != bytes.length; i++) { value ^= (bytes[i] & 0xff) << (i % 4); } return value; } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof ASN1Integer)) { return false; } ASN1Integer other = (ASN1Integer)o; return Arrays.areEqual(bytes, other.bytes); } public String toString() { return getValue().toString(); } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_1
crossvul-java_data_bad_4759_4
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.RIPEMD160Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.ECDSASigner; import org.bouncycastle.crypto.signers.ECNRSigner; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; import org.bouncycastle.jcajce.provider.asymmetric.util.DSABase; import org.bouncycastle.jcajce.provider.asymmetric.util.DSAEncoder; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; public class SignatureSpi extends DSABase { SignatureSpi(Digest digest, DSA signer, DSAEncoder encoder) { super(digest, signer, encoder); } protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { CipherParameters param = ECUtils.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = ECUtil.generatePrivateKeyParameter(privateKey); digest.reset(); if (appRandom != null) { signer.init(true, new ParametersWithRandom(param, appRandom)); } else { signer.init(true, param); } } static public class ecDSA extends SignatureSpi { public ecDSA() { super(new SHA1Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA extends SignatureSpi { public ecDetDSA() { super(new SHA1Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA1Digest())), new StdDSAEncoder()); } } static public class ecDSAnone extends SignatureSpi { public ecDSAnone() { super(new NullDigest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDSA224 extends SignatureSpi { public ecDSA224() { super(new SHA224Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA224 extends SignatureSpi { public ecDetDSA224() { super(new SHA224Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA224Digest())), new StdDSAEncoder()); } } static public class ecDSA256 extends SignatureSpi { public ecDSA256() { super(new SHA256Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA256 extends SignatureSpi { public ecDetDSA256() { super(new SHA256Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())), new StdDSAEncoder()); } } static public class ecDSA384 extends SignatureSpi { public ecDSA384() { super(new SHA384Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA384 extends SignatureSpi { public ecDetDSA384() { super(new SHA384Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA384Digest())), new StdDSAEncoder()); } } static public class ecDSA512 extends SignatureSpi { public ecDSA512() { super(new SHA512Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA512 extends SignatureSpi { public ecDetDSA512() { super(new SHA512Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA512Digest())), new StdDSAEncoder()); } } static public class ecDSASha3_224 extends SignatureSpi { public ecDSASha3_224() { super(new SHA3Digest(224), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_224 extends SignatureSpi { public ecDetDSASha3_224() { super(new SHA3Digest(224), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(224))), new StdDSAEncoder()); } } static public class ecDSASha3_256 extends SignatureSpi { public ecDSASha3_256() { super(new SHA3Digest(256), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_256 extends SignatureSpi { public ecDetDSASha3_256() { super(new SHA3Digest(256), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(256))), new StdDSAEncoder()); } } static public class ecDSASha3_384 extends SignatureSpi { public ecDSASha3_384() { super(new SHA3Digest(384), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_384 extends SignatureSpi { public ecDetDSASha3_384() { super(new SHA3Digest(384), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(384))), new StdDSAEncoder()); } } static public class ecDSASha3_512 extends SignatureSpi { public ecDSASha3_512() { super(new SHA3Digest(512), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_512 extends SignatureSpi { public ecDetDSASha3_512() { super(new SHA3Digest(512), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(512))), new StdDSAEncoder()); } } static public class ecDSARipeMD160 extends SignatureSpi { public ecDSARipeMD160() { super(new RIPEMD160Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecNR extends SignatureSpi { public ecNR() { super(new SHA1Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR224 extends SignatureSpi { public ecNR224() { super(new SHA224Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR256 extends SignatureSpi { public ecNR256() { super(new SHA256Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR384 extends SignatureSpi { public ecNR384() { super(new SHA384Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR512 extends SignatureSpi { public ecNR512() { super(new SHA512Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecCVCDSA extends SignatureSpi { public ecCVCDSA() { super(new SHA1Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA224 extends SignatureSpi { public ecCVCDSA224() { super(new SHA224Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA256 extends SignatureSpi { public ecCVCDSA256() { super(new SHA256Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA384 extends SignatureSpi { public ecCVCDSA384() { super(new SHA384Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA512 extends SignatureSpi { public ecCVCDSA512() { super(new SHA512Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecPlainDSARP160 extends SignatureSpi { public ecPlainDSARP160() { super(new RIPEMD160Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } private static class StdDSAEncoder implements DSAEncoder { public byte[] encode( BigInteger r, BigInteger s) throws IOException { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(r)); v.add(new ASN1Integer(s)); return new DERSequence(v).getEncoded(ASN1Encoding.DER); } public BigInteger[] decode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); BigInteger[] sig = new BigInteger[2]; sig[0] = ASN1Integer.getInstance(s.getObjectAt(0)).getValue(); sig[1] = ASN1Integer.getInstance(s.getObjectAt(1)).getValue(); return sig; } } private static class PlainDSAEncoder implements DSAEncoder { public byte[] encode( BigInteger r, BigInteger s) throws IOException { byte[] first = makeUnsigned(r); byte[] second = makeUnsigned(s); byte[] res; if (first.length > second.length) { res = new byte[first.length * 2]; } else { res = new byte[second.length * 2]; } System.arraycopy(first, 0, res, res.length / 2 - first.length, first.length); System.arraycopy(second, 0, res, res.length - second.length, second.length); return res; } private byte[] makeUnsigned(BigInteger val) { byte[] res = val.toByteArray(); if (res[0] == 0) { byte[] tmp = new byte[res.length - 1]; System.arraycopy(res, 1, tmp, 0, tmp.length); return tmp; } return res; } public BigInteger[] decode( byte[] encoding) throws IOException { BigInteger[] sig = new BigInteger[2]; byte[] first = new byte[encoding.length / 2]; byte[] second = new byte[encoding.length / 2]; System.arraycopy(encoding, 0, first, 0, first.length); System.arraycopy(encoding, first.length, second, 0, second.length); sig[0] = new BigInteger(1, first); sig[1] = new BigInteger(1, second); return sig; } } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_4
crossvul-java_data_good_4754_0
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.SignatureSpi; import java.security.spec.AlgorithmParameterSpec; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; public class DSASigner extends SignatureSpi implements PKCSObjectIdentifiers, X509ObjectIdentifiers { private Digest digest; private DSA signer; private SecureRandom random; protected DSASigner( Digest digest, DSA signer) { this.digest = digest; this.signer = signer; } protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey, SecureRandom random) throws InvalidKeyException { this.random = random; engineInitSign(privateKey); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePrivateKeyParameter(privateKey); if (random != null) { param = new ParametersWithRandom(param, random); } digest.reset(); signer.init(true, param); } protected void engineUpdate( byte b) throws SignatureException { digest.update(b); } protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { digest.update(b, off, len); } protected byte[] engineSign() throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { BigInteger[] sig = signer.generateSignature(hash); return derEncode(sig[0], sig[1]); } catch (Exception e) { throw new SignatureException(e.toString()); } } protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); } protected void engineSetParameter( AlgorithmParameterSpec params) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> */ protected void engineSetParameter( String param, Object value) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated */ protected Object engineGetParameter( String param) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } private byte[] derEncode( BigInteger r, BigInteger s) throws IOException { ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; return new DERSequence(rs).getEncoded(ASN1Encoding.DER); } private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } return new BigInteger[]{ ((ASN1Integer)s.getObjectAt(0)).getValue(), ((ASN1Integer)s.getObjectAt(1)).getValue() }; } static public class stdDSA extends DSASigner { public stdDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA extends DSASigner { public detDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA1Digest()))); } } static public class dsa224 extends DSASigner { public dsa224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA224 extends DSASigner { public detDSA224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA224Digest()))); } } static public class dsa256 extends DSASigner { public dsa256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA256 extends DSASigner { public detDSA256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA256Digest()))); } } static public class dsa384 extends DSASigner { public dsa384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA384 extends DSASigner { public detDSA384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA384Digest()))); } } static public class dsa512 extends DSASigner { public dsa512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA512 extends DSASigner { public detDSA512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA512Digest()))); } } static public class dsaSha3_224 extends DSASigner { public dsaSha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_224 extends DSASigner { public detDSASha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(224)))); } } static public class dsaSha3_256 extends DSASigner { public dsaSha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_256 extends DSASigner { public detDSASha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(256)))); } } static public class dsaSha3_384 extends DSASigner { public dsaSha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_384 extends DSASigner { public detDSASha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(384)))); } } static public class dsaSha3_512 extends DSASigner { public dsaSha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_512 extends DSASigner { public detDSASha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(512)))); } } static public class noneDSA extends DSASigner { public noneDSA() { super(new NullDigest(), new org.bouncycastle.crypto.signers.DSASigner()); } } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4754_0
crossvul-java_data_good_4754_1
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4754_1
crossvul-java_data_good_4759_1
package org.bouncycastle.asn1; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.util.Arrays; /** * Class representing the ASN.1 INTEGER type. */ public class ASN1Integer extends ASN1Primitive { private final byte[] bytes; /** * return an integer from the passed in object * * @param obj an ASN1Integer or an object that can be converted into one. * @throws IllegalArgumentException if the object cannot be converted. * @return an ASN1Integer instance. */ public static ASN1Integer getInstance( Object obj) { if (obj == null || obj instanceof ASN1Integer) { return (ASN1Integer)obj; } if (obj instanceof byte[]) { try { return (ASN1Integer)fromByteArray((byte[])obj); } catch (Exception e) { throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); } } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an Integer from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @throws IllegalArgumentException if the tagged object cannot * be converted. * @return an ASN1Integer instance. */ public static ASN1Integer getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof ASN1Integer) { return getInstance(o); } else { return new ASN1Integer(ASN1OctetString.getInstance(obj.getObject()).getOctets()); } } public ASN1Integer( long value) { bytes = BigInteger.valueOf(value).toByteArray(); } public ASN1Integer( BigInteger value) { bytes = value.toByteArray(); } public ASN1Integer( byte[] bytes) { this(bytes, true); } ASN1Integer(byte[] bytes, boolean clone) { if (bytes.length > 1) { if (bytes[0] == 0 && (bytes[1] & 0x80) == 0) { throw new IllegalArgumentException("malformed integer"); } if (bytes[0] == (byte)0xff && (bytes[1] & 0x80) != 0) { throw new IllegalArgumentException("malformed integer"); } } this.bytes = (clone) ? Arrays.clone(bytes) : bytes; } public BigInteger getValue() { return new BigInteger(bytes); } /** * in some cases positive values get crammed into a space, * that's not quite big enough... * @return the BigInteger that results from treating this ASN.1 INTEGER as unsigned. */ public BigInteger getPositiveValue() { return new BigInteger(1, bytes); } boolean isConstructed() { return false; } int encodedLength() { return 1 + StreamUtil.calculateBodyLength(bytes.length) + bytes.length; } void encode( ASN1OutputStream out) throws IOException { out.writeEncoded(BERTags.INTEGER, bytes); } public int hashCode() { int value = 0; for (int i = 0; i != bytes.length; i++) { value ^= (bytes[i] & 0xff) << (i % 4); } return value; } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof ASN1Integer)) { return false; } ASN1Integer other = (ASN1Integer)o; return Arrays.areEqual(bytes, other.bytes); } public String toString() { return getValue().toString(); } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_1
crossvul-java_data_good_4759_4
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.RIPEMD160Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.ECDSASigner; import org.bouncycastle.crypto.signers.ECNRSigner; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; import org.bouncycastle.jcajce.provider.asymmetric.util.DSABase; import org.bouncycastle.jcajce.provider.asymmetric.util.DSAEncoder; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.util.Arrays; public class SignatureSpi extends DSABase { SignatureSpi(Digest digest, DSA signer, DSAEncoder encoder) { super(digest, signer, encoder); } protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { CipherParameters param = ECUtils.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = ECUtil.generatePrivateKeyParameter(privateKey); digest.reset(); if (appRandom != null) { signer.init(true, new ParametersWithRandom(param, appRandom)); } else { signer.init(true, param); } } static public class ecDSA extends SignatureSpi { public ecDSA() { super(new SHA1Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA extends SignatureSpi { public ecDetDSA() { super(new SHA1Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA1Digest())), new StdDSAEncoder()); } } static public class ecDSAnone extends SignatureSpi { public ecDSAnone() { super(new NullDigest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDSA224 extends SignatureSpi { public ecDSA224() { super(new SHA224Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA224 extends SignatureSpi { public ecDetDSA224() { super(new SHA224Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA224Digest())), new StdDSAEncoder()); } } static public class ecDSA256 extends SignatureSpi { public ecDSA256() { super(new SHA256Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA256 extends SignatureSpi { public ecDetDSA256() { super(new SHA256Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())), new StdDSAEncoder()); } } static public class ecDSA384 extends SignatureSpi { public ecDSA384() { super(new SHA384Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA384 extends SignatureSpi { public ecDetDSA384() { super(new SHA384Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA384Digest())), new StdDSAEncoder()); } } static public class ecDSA512 extends SignatureSpi { public ecDSA512() { super(new SHA512Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSA512 extends SignatureSpi { public ecDetDSA512() { super(new SHA512Digest(), new ECDSASigner(new HMacDSAKCalculator(new SHA512Digest())), new StdDSAEncoder()); } } static public class ecDSASha3_224 extends SignatureSpi { public ecDSASha3_224() { super(new SHA3Digest(224), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_224 extends SignatureSpi { public ecDetDSASha3_224() { super(new SHA3Digest(224), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(224))), new StdDSAEncoder()); } } static public class ecDSASha3_256 extends SignatureSpi { public ecDSASha3_256() { super(new SHA3Digest(256), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_256 extends SignatureSpi { public ecDetDSASha3_256() { super(new SHA3Digest(256), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(256))), new StdDSAEncoder()); } } static public class ecDSASha3_384 extends SignatureSpi { public ecDSASha3_384() { super(new SHA3Digest(384), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_384 extends SignatureSpi { public ecDetDSASha3_384() { super(new SHA3Digest(384), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(384))), new StdDSAEncoder()); } } static public class ecDSASha3_512 extends SignatureSpi { public ecDSASha3_512() { super(new SHA3Digest(512), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecDetDSASha3_512 extends SignatureSpi { public ecDetDSASha3_512() { super(new SHA3Digest(512), new ECDSASigner(new HMacDSAKCalculator(new SHA3Digest(512))), new StdDSAEncoder()); } } static public class ecDSARipeMD160 extends SignatureSpi { public ecDSARipeMD160() { super(new RIPEMD160Digest(), new ECDSASigner(), new StdDSAEncoder()); } } static public class ecNR extends SignatureSpi { public ecNR() { super(new SHA1Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR224 extends SignatureSpi { public ecNR224() { super(new SHA224Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR256 extends SignatureSpi { public ecNR256() { super(new SHA256Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR384 extends SignatureSpi { public ecNR384() { super(new SHA384Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecNR512 extends SignatureSpi { public ecNR512() { super(new SHA512Digest(), new ECNRSigner(), new StdDSAEncoder()); } } static public class ecCVCDSA extends SignatureSpi { public ecCVCDSA() { super(new SHA1Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA224 extends SignatureSpi { public ecCVCDSA224() { super(new SHA224Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA256 extends SignatureSpi { public ecCVCDSA256() { super(new SHA256Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA384 extends SignatureSpi { public ecCVCDSA384() { super(new SHA384Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecCVCDSA512 extends SignatureSpi { public ecCVCDSA512() { super(new SHA512Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } static public class ecPlainDSARP160 extends SignatureSpi { public ecPlainDSARP160() { super(new RIPEMD160Digest(), new ECDSASigner(), new PlainDSAEncoder()); } } private static class StdDSAEncoder implements DSAEncoder { public byte[] encode( BigInteger r, BigInteger s) throws IOException { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(r)); v.add(new ASN1Integer(s)); return new DERSequence(v).getEncoded(ASN1Encoding.DER); } public BigInteger[] decode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER))) { throw new IOException("malformed signature"); } BigInteger[] sig = new BigInteger[2]; sig[0] = ASN1Integer.getInstance(s.getObjectAt(0)).getValue(); sig[1] = ASN1Integer.getInstance(s.getObjectAt(1)).getValue(); return sig; } } private static class PlainDSAEncoder implements DSAEncoder { public byte[] encode( BigInteger r, BigInteger s) throws IOException { byte[] first = makeUnsigned(r); byte[] second = makeUnsigned(s); byte[] res; if (first.length > second.length) { res = new byte[first.length * 2]; } else { res = new byte[second.length * 2]; } System.arraycopy(first, 0, res, res.length / 2 - first.length, first.length); System.arraycopy(second, 0, res, res.length - second.length, second.length); return res; } private byte[] makeUnsigned(BigInteger val) { byte[] res = val.toByteArray(); if (res[0] == 0) { byte[] tmp = new byte[res.length - 1]; System.arraycopy(res, 1, tmp, 0, tmp.length); return tmp; } return res; } public BigInteger[] decode( byte[] encoding) throws IOException { BigInteger[] sig = new BigInteger[2]; byte[] first = new byte[encoding.length / 2]; byte[] second = new byte[encoding.length / 2]; System.arraycopy(encoding, 0, first, 0, first.length); System.arraycopy(encoding, first.length, second, 0, second.length); sig[0] = new BigInteger(1, first); sig[1] = new BigInteger(1, second); return sig; } } }
./CrossVul/dataset_final_sorted/CWE-347/java/good_4759_4
crossvul-java_data_bad_4759_3
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.SignatureSpi; import java.security.spec.AlgorithmParameterSpec; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.NullDigest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.HMacDSAKCalculator; public class DSASigner extends SignatureSpi implements PKCSObjectIdentifiers, X509ObjectIdentifiers { private Digest digest; private DSA signer; private SecureRandom random; protected DSASigner( Digest digest, DSA signer) { this.digest = digest; this.signer = signer; } protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePublicKeyParameter(publicKey); digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey, SecureRandom random) throws InvalidKeyException { this.random = random; engineInitSign(privateKey); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param = DSAUtil.generatePrivateKeyParameter(privateKey); if (random != null) { param = new ParametersWithRandom(param, random); } digest.reset(); signer.init(true, param); } protected void engineUpdate( byte b) throws SignatureException { digest.update(b); } protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { digest.update(b, off, len); } protected byte[] engineSign() throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { BigInteger[] sig = signer.generateSignature(hash); return derEncode(sig[0], sig[1]); } catch (Exception e) { throw new SignatureException(e.toString()); } } protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); } protected void engineSetParameter( AlgorithmParameterSpec params) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> */ protected void engineSetParameter( String param, Object value) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated */ protected Object engineGetParameter( String param) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } private byte[] derEncode( BigInteger r, BigInteger s) throws IOException { ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; return new DERSequence(rs).getEncoded(ASN1Encoding.DER); } private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); if (s.size() != 2) { throw new IOException("malformed signature"); } return new BigInteger[]{ ((ASN1Integer)s.getObjectAt(0)).getValue(), ((ASN1Integer)s.getObjectAt(1)).getValue() }; } static public class stdDSA extends DSASigner { public stdDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA extends DSASigner { public detDSA() { super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA1Digest()))); } } static public class dsa224 extends DSASigner { public dsa224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA224 extends DSASigner { public detDSA224() { super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA224Digest()))); } } static public class dsa256 extends DSASigner { public dsa256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA256 extends DSASigner { public detDSA256() { super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA256Digest()))); } } static public class dsa384 extends DSASigner { public dsa384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA384 extends DSASigner { public detDSA384() { super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA384Digest()))); } } static public class dsa512 extends DSASigner { public dsa512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSA512 extends DSASigner { public detDSA512() { super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA512Digest()))); } } static public class dsaSha3_224 extends DSASigner { public dsaSha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_224 extends DSASigner { public detDSASha3_224() { super(new SHA3Digest(224), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(224)))); } } static public class dsaSha3_256 extends DSASigner { public dsaSha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_256 extends DSASigner { public detDSASha3_256() { super(new SHA3Digest(256), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(256)))); } } static public class dsaSha3_384 extends DSASigner { public dsaSha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_384 extends DSASigner { public detDSASha3_384() { super(new SHA3Digest(384), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(384)))); } } static public class dsaSha3_512 extends DSASigner { public dsaSha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner()); } } static public class detDSASha3_512 extends DSASigner { public detDSASha3_512() { super(new SHA3Digest(512), new org.bouncycastle.crypto.signers.DSASigner(new HMacDSAKCalculator(new SHA3Digest(512)))); } } static public class noneDSA extends DSASigner { public noneDSA() { super(new NullDigest(), new org.bouncycastle.crypto.signers.DSASigner()); } } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_3
crossvul-java_data_bad_4759_2
package org.bouncycastle.asn1.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.BERSequence; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.misc.CAST5CBCParameters; import org.bouncycastle.asn1.misc.IDEACBCPar; import org.bouncycastle.asn1.misc.NetscapeCertType; import org.bouncycastle.asn1.misc.NetscapeRevocationURL; import org.bouncycastle.asn1.misc.VerisignCzagExtension; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; public class MiscTest extends SimpleTest { private boolean isSameAs( byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public void shouldFailOnExtraData() throws Exception { // basic construction DERBitString s1 = new DERBitString(new byte[0], 0); ASN1Primitive.fromByteArray(s1.getEncoded()); ASN1Primitive.fromByteArray(new BERSequence(s1).getEncoded()); try { ASN1Primitive obj = ASN1Primitive.fromByteArray(Arrays.concatenate(s1.getEncoded(), new byte[1])); fail("no exception"); } catch (IOException e) { if (!"Extra data detected in stream".equals(e.getMessage())) { fail("wrong exception"); } } } public void performTest() throws Exception { byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 }; ASN1Encodable[] values = { new CAST5CBCParameters(testIv, 128), new NetscapeCertType(NetscapeCertType.smime), new VerisignCzagExtension(new DERIA5String("hello")), new IDEACBCPar(testIv), new NetscapeRevocationURL(new DERIA5String("http://test")) }; byte[] data = Base64.decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA=="); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } ASN1Primitive[] readValues = new ASN1Primitive[values.length]; if (!isSameAs(bOut.toByteArray(), data)) { fail("Failed data check"); } ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { ASN1Primitive o = aIn.readObject(); if (!values[i].equals(o)) { fail("Failed equality test for " + o); } if (o.hashCode() != values[i].hashCode()) { fail("Failed hashCode test for " + o); } } shouldFailOnExtraData(); } public String getName() { return "Misc"; } public static void main( String[] args) { runTest(new MiscTest()); } }
./CrossVul/dataset_final_sorted/CWE-347/java/bad_4759_2
crossvul-java_data_bad_3993_0
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.api; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.bigbluebutton.api.domain.Recording; import org.bigbluebutton.api.domain.RecordingMetadata; import org.bigbluebutton.api.messaging.messages.MakePresentationDownloadableMsg; import org.bigbluebutton.api.util.RecordingMetadataReaderHelper; import org.bigbluebutton.api2.domain.UploadedTrack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecordingService { private static Logger log = LoggerFactory.getLogger(RecordingService.class); private static String processDir = "/var/bigbluebutton/recording/process"; private static String publishedDir = "/var/bigbluebutton/published"; private static String unpublishedDir = "/var/bigbluebutton/unpublished"; private static String deletedDir = "/var/bigbluebutton/deleted"; private RecordingMetadataReaderHelper recordingServiceHelper; private String recordStatusDir; private String captionsDir; private String presentationBaseDir; private String defaultServerUrl; private String defaultTextTrackUrl; private void copyPresentationFile(File presFile, File dlownloadableFile) { try { FileUtils.copyFile(presFile, dlownloadableFile); } catch (IOException ex) { log.error("Failed to copy file: {}", ex); } } public void processMakePresentationDownloadableMsg(MakePresentationDownloadableMsg msg) { File presDir = Util.getPresentationDir(presentationBaseDir, msg.meetingId, msg.presId); File downloadableFile = new File(presDir.getAbsolutePath() + File.separatorChar + msg.presFilename); if (presDir != null) { if (msg.downloadable) { String fileExt = FilenameUtils.getExtension(msg.presFilename); File presFile = new File(presDir.getAbsolutePath() + File.separatorChar + msg.presId + "." + fileExt); log.info("Make file downloadable. {}", downloadableFile.getAbsolutePath()); copyPresentationFile(presFile, downloadableFile); } else { if (downloadableFile.exists()) { if(downloadableFile.delete()) { log.info("File deleted. {}", downloadableFile.getAbsolutePath()); } else { log.warn("Failed to delete. {}", downloadableFile.getAbsolutePath()); } } } } } public File getDownloadablePresentationFile(String meetingId, String presId, String presFilename) { log.info("Find downloadable presentation for meetingId={} presId={} filename={}", meetingId, presId, presFilename); File presDir = Util.getPresentationDir(presentationBaseDir, meetingId, presId); return new File(presDir.getAbsolutePath() + File.separatorChar + presFilename); } public void kickOffRecordingChapterBreak(String meetingId, Long timestamp) { String done = recordStatusDir + File.separatorChar + meetingId + "-" + timestamp + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create {} file.", done); } catch (IOException e) { log.error("Exception occured when trying to create {} file", done); } } else { log.error("{} file already exists.", done); } } public void startIngestAndProcessing(String meetingId) { String done = recordStatusDir + File.separatorChar + meetingId + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create {} file.", done); } catch (IOException e) { log.error("Exception occured when trying to create {} file.", done); } } else { log.error("{} file already exists.", done); } } public void markAsEnded(String meetingId) { String done = recordStatusDir + "/../ended/" + meetingId + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create " + done + " file."); } catch (IOException e) { log.error("Exception occured when trying to create {} file.", done); } } else { log.error(done + " file already exists."); } } public List<RecordingMetadata> getRecordingsMetadata(List<String> recordIDs, List<String> states) { List<RecordingMetadata> recs = new ArrayList<>(); Map<String, List<File>> allDirectories = getAllDirectories(states); if (recordIDs.isEmpty()) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { recordIDs.addAll(getAllRecordingIds(entry.getValue())); } } for (String recordID : recordIDs) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { List<File> _recs = getRecordingsForPath(recordID, entry.getValue()); for (File _rec : _recs) { RecordingMetadata r = getRecordingMetadata(_rec); if (r != null) { recs.add(r); } } } } return recs; } public Boolean validateTextTrackSingleUseToken(String recordId, String caption, String token) { return recordingServiceHelper.validateTextTrackSingleUseToken(recordId, caption, token); } public String getRecordingTextTracks(String recordId) { return recordingServiceHelper.getRecordingTextTracks(recordId, captionsDir, getCaptionFileUrlDirectory()); } public String putRecordingTextTrack(UploadedTrack track) { return recordingServiceHelper.putRecordingTextTrack(track); } public String getRecordings2x(List<String> idList, List<String> states, Map<String, String> metadataFilters) { List<RecordingMetadata> recsList = getRecordingsMetadata(idList, states); ArrayList<RecordingMetadata> recs = filterRecordingsByMetadata(recsList, metadataFilters); return recordingServiceHelper.getRecordings2x(recs); } private RecordingMetadata getRecordingMetadata(File dir) { File file = new File(dir.getPath() + File.separatorChar + "metadata.xml"); return recordingServiceHelper.getRecordingMetadata(file); } public boolean recordingMatchesMetadata(RecordingMetadata recording, Map<String, String> metadataFilters) { boolean matchesMetadata = true; Map<String, String> recMeta = recording.getMeta(); for (Map.Entry<String, String> filter : metadataFilters.entrySet()) { String metadataValue = recMeta.get(filter.getKey()); if ( metadataValue == null ) { // The recording doesn't have metadata specified matchesMetadata = false; } else { String filterValue = filter.getValue(); if( filterValue.charAt(0) == '%' && filterValue.charAt(filterValue.length()-1) == '%' && metadataValue.contains(filterValue.substring(1, filterValue.length()-1)) ){ // Filter value embraced by two wild cards // AND the filter value is part of the metadata value } else if( filterValue.charAt(0) == '%' && metadataValue.endsWith(filterValue.substring(1, filterValue.length())) ) { // Filter value starts with a wild cards // AND the filter value ends with the metadata value } else if( filterValue.charAt(filterValue.length()-1) == '%' && metadataValue.startsWith(filterValue.substring(0, filterValue.length()-1)) ) { // Filter value ends with a wild cards // AND the filter value starts with the metadata value } else if( metadataValue.equals(filterValue) ) { // Filter value doesnt have wildcards // AND the filter value is the same as metadata value } else { matchesMetadata = false; } } } return matchesMetadata; } public ArrayList<RecordingMetadata> filterRecordingsByMetadata(List<RecordingMetadata> recordings, Map<String, String> metadataFilters) { ArrayList<RecordingMetadata> resultRecordings = new ArrayList<>(); for (RecordingMetadata entry : recordings) { if (recordingMatchesMetadata(entry, metadataFilters)) resultRecordings.add(entry); } return resultRecordings; } private ArrayList<File> getAllRecordingsFor(String recordId) { String[] format = getPlaybackFormats(publishedDir); ArrayList<File> ids = new ArrayList<File>(); for (int i = 0; i < format.length; i++) { List<File> recordings = getDirectories(publishedDir + File.separatorChar + format[i]); for (int f = 0; f < recordings.size(); f++) { if (recordId.equals(recordings.get(f).getName())) ids.add(recordings.get(f)); } } return ids; } public boolean isRecordingExist(String recordId) { List<String> publishList = getAllRecordingIds(publishedDir); List<String> unpublishList = getAllRecordingIds(unpublishedDir); if (publishList.contains(recordId) || unpublishList.contains(recordId)) { return true; } return false; } public boolean existAnyRecording(List<String> idList) { List<String> publishList = getAllRecordingIds(publishedDir); List<String> unpublishList = getAllRecordingIds(unpublishedDir); for (String id : idList) { if (publishList.contains(id) || unpublishList.contains(id)) { return true; } } return false; } private List<String> getAllRecordingIds(String path) { String[] format = getPlaybackFormats(path); return getAllRecordingIds(path, format); } private List<String> getAllRecordingIds(String path, String[] format) { List<String> ids = new ArrayList<>(); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (!ids.contains(recording.getName())) { ids.add(recording.getName()); } } } return ids; } private Set<String> getAllRecordingIds(List<File> recs) { Set<String> ids = new HashSet<>(); Iterator<File> iterator = recs.iterator(); while (iterator.hasNext()) { ids.add(iterator.next().getName()); } return ids; } private List<File> getRecordingsForPath(String id, List<File> recordings) { List<File> recs = new ArrayList<>(); Iterator<File> iterator = recordings.iterator(); while (iterator.hasNext()) { File rec = iterator.next(); if (rec.getName().startsWith(id)) { recs.add(rec); } } return recs; } private static void deleteRecording(String id, String path) { String[] format = getPlaybackFormats(path); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (recording.getName().equals(id)) { deleteDirectory(recording); createDirectory(recording); } } } } private static void createDirectory(File directory) { if (!directory.exists()) directory.mkdirs(); } private static void deleteDirectory(File directory) { /** * Go through each directory and check if it's not empty. We need to * delete files inside a directory before a directory can be deleted. **/ File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } // Now that the directory is empty. Delete it. directory.delete(); } private static List<File> getDirectories(String path) { List<File> files = new ArrayList<>(); try { DirectoryStream<Path> stream = Files.newDirectoryStream(FileSystems.getDefault().getPath(path)); Iterator<Path> iter = stream.iterator(); while (iter.hasNext()) { Path next = iter.next(); files.add(next.toFile()); } stream.close(); } catch (IOException e) { e.printStackTrace(); } return files; } private static String[] getPlaybackFormats(String path) { System.out.println("Getting playback formats at " + path); List<File> dirs = getDirectories(path); String[] formats = new String[dirs.size()]; for (int i = 0; i < dirs.size(); i++) { System.out.println("Playback format = " + dirs.get(i).getName()); formats[i] = dirs.get(i).getName(); } return formats; } public void setRecordingStatusDir(String dir) { recordStatusDir = dir; } public void setUnpublishedDir(String dir) { unpublishedDir = dir; } public void setPresentationBaseDir(String dir) { presentationBaseDir = dir; } public void setDefaultServerUrl(String url) { defaultServerUrl = url; } public void setDefaultTextTrackUrl(String url) { defaultTextTrackUrl = url; } public void setPublishedDir(String dir) { publishedDir = dir; } public void setCaptionsDir(String dir) { captionsDir = dir; } public void setRecordingServiceHelper(RecordingMetadataReaderHelper r) { recordingServiceHelper = r; } private boolean shouldIncludeState(List<String> states, String type) { boolean r = false; if (!states.isEmpty()) { if (states.contains("any")) { r = true; } else { if (type.equals(Recording.STATE_PUBLISHED) && states.contains(Recording.STATE_PUBLISHED)) { r = true; } else if (type.equals(Recording.STATE_UNPUBLISHED) && states.contains(Recording.STATE_UNPUBLISHED)) { r = true; } else if (type.equals(Recording.STATE_DELETED) && states.contains(Recording.STATE_DELETED)) { r = true; } else if (type.equals(Recording.STATE_PROCESSING) && states.contains(Recording.STATE_PROCESSING)) { r = true; } else if (type.equals(Recording.STATE_PROCESSED) && states.contains(Recording.STATE_PROCESSED)) { r = true; } } } else { if (type.equals(Recording.STATE_PUBLISHED) || type.equals(Recording.STATE_UNPUBLISHED)) { r = true; } } return r; } public boolean changeState(String recordingId, String state) { boolean succeeded = false; if (state.equals(Recording.STATE_PUBLISHED)) { // It can only be published if it is unpublished succeeded |= changeState(unpublishedDir, recordingId, state); } else if (state.equals(Recording.STATE_UNPUBLISHED)) { // It can only be unpublished if it is published succeeded |= changeState(publishedDir, recordingId, state); } else if (state.equals(Recording.STATE_DELETED)) { // It can be deleted from any state succeeded |= changeState(publishedDir, recordingId, state); succeeded |= changeState(unpublishedDir, recordingId, state); } return succeeded; } private boolean changeState(String path, String recordingId, String state) { boolean exists = false; boolean succeeded = true; String[] format = getPlaybackFormats(path); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (recording.getName().equalsIgnoreCase(recordingId)) { exists = true; File dest; if (state.equals(Recording.STATE_PUBLISHED)) { dest = new File(publishedDir + File.separatorChar + aFormat); succeeded &= publishRecording(dest, recordingId, recording, aFormat); } else if (state.equals(Recording.STATE_UNPUBLISHED)) { dest = new File(unpublishedDir + File.separatorChar + aFormat); succeeded &= unpublishRecording(dest, recordingId, recording, aFormat); } else if (state.equals(Recording.STATE_DELETED)) { dest = new File(deletedDir + File.separatorChar + aFormat); succeeded &= deleteRecording(dest, recordingId, recording, aFormat); } else { log.debug(String.format("State: %s, is not supported", state)); return false; } } } } return exists && succeeded; } public boolean publishRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_PUBLISHED); r.setPublished(true); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to publish recording : " + recordingId, e); } } return false; } public boolean unpublishRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_UNPUBLISHED); r.setPublished(false); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to unpublish recording : " + recordingId, e); } } return false; } public boolean deleteRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_DELETED); r.setPublished(false); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to delete recording : " + recordingId, e); } } return false; } private List<File> getAllDirectories(String state) { List<File> allDirectories = new ArrayList<>(); String dir = getDestinationBaseDirectoryName(state); if ( dir != null ) { String[] formats = getPlaybackFormats(dir); for (String format : formats) { allDirectories.addAll(getDirectories(dir + File.separatorChar + format)); } } return allDirectories; } private Map<String, List<File>> getAllDirectories(List<String> states) { Map<String, List<File>> allDirectories = new HashMap<>(); if ( shouldIncludeState(states, Recording.STATE_PUBLISHED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PUBLISHED); allDirectories.put(Recording.STATE_PUBLISHED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_UNPUBLISHED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_UNPUBLISHED); allDirectories.put(Recording.STATE_UNPUBLISHED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_DELETED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_DELETED); allDirectories.put(Recording.STATE_DELETED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_PROCESSING) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PROCESSING); allDirectories.put(Recording.STATE_PROCESSING, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_PROCESSED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PROCESSED); allDirectories.put(Recording.STATE_PROCESSED, listedDirectories); } return allDirectories; } public void updateMetaParams(List<String> recordIDs, Map<String,String> metaParams) { // Define the directories used to lookup the recording List<String> states = new ArrayList<>(); states.add(Recording.STATE_PUBLISHED); states.add(Recording.STATE_UNPUBLISHED); states.add(Recording.STATE_DELETED); // Gather all the existent directories based on the states defined for the lookup Map<String, List<File>> allDirectories = getAllDirectories(states); // Retrieve the actual recording from the directories gathered for the lookup for (String recordID : recordIDs) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { List<File> recs = getRecordingsForPath(recordID, entry.getValue()); // Go through all recordings of all formats for (File rec : recs) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(rec.getPath()); updateRecordingMetadata(metadataXml, metaParams, metadataXml); } } } } public void updateRecordingMetadata(File srxMetadataXml, Map<String,String> metaParams, File destMetadataXml) { RecordingMetadata rec = recordingServiceHelper.getRecordingMetadata(srxMetadataXml); Map<String, String> recMeta = rec.getMeta(); if (rec != null && !recMeta.isEmpty()) { for (Map.Entry<String,String> meta : metaParams.entrySet()) { if ( !"".equals(meta.getValue()) ) { // As it has a value, if the meta parameter exists update it, otherwise add it recMeta.put(meta.getKey(), meta.getValue()); } else { // As it doesn't have a value, if it exists delete it if ( recMeta.containsKey(meta.getKey()) ) { recMeta.remove(meta.getKey()); } } } rec.setMeta(recMeta); // Process the changes by saving the recording into metadata.xml recordingServiceHelper.saveRecordingMetadata(destMetadataXml, rec); } } private Map<String,File> indexRecordings(List<File> recs) { Map<String,File> indexedRecs = new HashMap<>(); Iterator<File> iterator = recs.iterator(); while (iterator.hasNext()) { File rec = iterator.next(); indexedRecs.put(rec.getName(), rec); } return indexedRecs; } private String getDestinationBaseDirectoryName(String state) { return getDestinationBaseDirectoryName(state, false); } private String getDestinationBaseDirectoryName(String state, boolean forceDefault) { String baseDir = null; if ( state.equals(Recording.STATE_PROCESSING) || state.equals(Recording.STATE_PROCESSED) ) baseDir = processDir; else if ( state.equals(Recording.STATE_PUBLISHED) ) baseDir = publishedDir; else if ( state.equals(Recording.STATE_UNPUBLISHED) ) baseDir = unpublishedDir; else if ( state.equals(Recording.STATE_DELETED) ) baseDir = deletedDir; else if ( forceDefault ) baseDir = publishedDir; return baseDir; } public String getCaptionTrackInboxDir() { return captionsDir + File.separatorChar + "inbox"; } public String getCaptionsDir() { return captionsDir; } public String getCaptionFileUrlDirectory() { return defaultTextTrackUrl + "/textTrack/"; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_3993_0
crossvul-java_data_good_498_1
package cc.mrbird.common.exception; /** * 文件下载异常 */ public class FileDownloadException extends Exception { private static final long serialVersionUID = -3608667856397125671L; public FileDownloadException(String message) { super(message); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_498_1
crossvul-java_data_good_68_0
/** * Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zeroturnaround.zip; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeroturnaround.zip.commons.FileUtils; import org.zeroturnaround.zip.commons.FilenameUtils; import org.zeroturnaround.zip.commons.IOUtils; import org.zeroturnaround.zip.transform.ZipEntryTransformer; import org.zeroturnaround.zip.transform.ZipEntryTransformerEntry; /** * ZIP file manipulation utilities. * * @author Rein Raudjärv * @author Innokenty Shuvalov * * @see #containsEntry(File, String) * @see #unpackEntry(File, String) * @see #unpack(File, File) * @see #pack(File, File) */ public final class ZipUtil { private static final String PATH_SEPARATOR = "/"; /** Default compression level */ public static final int DEFAULT_COMPRESSION_LEVEL = Deflater.DEFAULT_COMPRESSION; // Use / instead of . to work around an issue with Maven Shade Plugin private static final Logger log = LoggerFactory.getLogger("org/zeroturnaround/zip/ZipUtil".replace('/', '.')); // NOSONAR private ZipUtil() { } /* Extracting single entries from ZIP files. */ /** * Checks if the ZIP file contains the given entry. * * @param zip * ZIP file. * @param name * entry name. * @return <code>true</code> if the ZIP file contains the given entry. */ public static boolean containsEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); return zf.getEntry(name) != null; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Returns the compression method of a given entry of the ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return Returns <code>ZipEntry.STORED</code>, <code>ZipEntry.DEFLATED</code> or -1 if * the ZIP file does not contain the given entry. * @deprecated The compression level cannot be retrieved. This method exists only to ensure backwards compatibility with ZipUtil version 1.9, which returned the compression * method, not the level. */ @Deprecated public static int getCompressionLevelOfEntry(File zip, String name) { return getCompressionMethodOfEntry(zip, name); } /** * Returns the compression method of a given entry of the ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return Returns <code>ZipEntry.STORED</code>, <code>ZipEntry.DEFLATED</code> or -1 if * the ZIP file does not contain the given entry. */ public static int getCompressionMethodOfEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); ZipEntry zipEntry = zf.getEntry(name); if (zipEntry == null) { return -1; } return zipEntry.getMethod(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Checks if the ZIP file contains any of the given entries. * * @param zip * ZIP file. * @param names * entry names. * @return <code>true</code> if the ZIP file contains any of the given * entries. */ public static boolean containsAnyEntry(File zip, String[] names) { ZipFile zf = null; try { zf = new ZipFile(zip); for (int i = 0; i < names.length; i++) { if (zf.getEntry(names[i]) != null) { return true; } } return false; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zip * ZIP file. * @param name * entry name. * * @param charset * charset to be used to process the zip * * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(File zip, String name, Charset charset) { ZipFile zf = null; try { if (charset != null) { zf = new ZipFile(zip, charset); } else { zf = new ZipFile(zip); } return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zf * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(ZipFile zf, String name) { try { return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Unpacks a single entry from a ZIP file. * * @param zf * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ private static byte[] doUnpackEntry(ZipFile zf, String name) throws IOException { ZipEntry ze = zf.getEntry(name); if (ze == null) { return null; // entry not found } InputStream is = zf.getInputStream(ze); try { return IOUtils.toByteArray(is); } finally { IOUtils.closeQuietly(is); } } /** * Unpacks a single entry from a ZIP stream. * * @param is * ZIP stream. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(InputStream is, String name) { ByteArrayUnpacker action = new ByteArrayUnpacker(); if (!handle(is, name, action)) return null; // entry not found return action.getBytes(); } /** * Copies an entry into a byte array. * * @author Rein Raudjärv */ private static class ByteArrayUnpacker implements ZipEntryCallback { private byte[] bytes; public void process(InputStream in, ZipEntry zipEntry) throws IOException { bytes = IOUtils.toByteArray(in); } public byte[] getBytes() { return bytes; } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zip * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(File zip, String name, File file) { return unpackEntry(zip, name, file, null); } /** * Unpacks a single file from a ZIP archive to a file. * * @param zip * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @param charset * charset to be used processing the zip * * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(File zip, String name, File file, Charset charset) { ZipFile zf = null; try { if (charset != null) { zf = new ZipFile(zip, charset); } else { zf = new ZipFile(zip); } return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zf * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(ZipFile zf, String name, File file) { try { return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zf * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ private static boolean doUnpackEntry(ZipFile zf, String name, File file) throws IOException { if (log.isTraceEnabled()) { log.trace("Extracting '" + zf.getName() + "' entry '" + name + "' into '" + file + "'."); } ZipEntry ze = zf.getEntry(name); if (ze == null) { return false; // entry not found } if (ze.isDirectory() || zf.getInputStream(ze) == null) { if (file.isDirectory()) { return true; } if (file.exists()) { FileUtils.forceDelete(file); } return file.mkdirs(); } InputStream in = new BufferedInputStream(zf.getInputStream(ze)); try { FileUtils.copy(in, file); } finally { IOUtils.closeQuietly(in); } return true; } /** * Unpacks a single file from a ZIP stream to a file. * * @param is * ZIP stream. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. * @throws java.io.IOException if file is not found or writing to it fails */ public static boolean unpackEntry(InputStream is, String name, File file) throws IOException { return handle(is, name, new FileUnpacker(file)); } /** * Copies an entry into a File. * * @author Rein Raudjärv */ private static class FileUnpacker implements ZipEntryCallback { private final File file; public FileUnpacker(File file) { this.file = file; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { FileUtils.copy(in, file); } } /* Traversing ZIP files */ /** * Reads the given ZIP file and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, ZipInfoCallback) */ public static void iterate(File zip, ZipEntryCallback action) { iterate(zip, action, null); } /** * Reads the given ZIP file and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @param charset * Charset used to processed the ZipFile with * * @see ZipEntryCallback * @see #iterate(File, ZipInfoCallback) */ public static void iterate(File zip, ZipEntryCallback action, Charset charset) { ZipFile zf = null; try { if (charset == null) { zf = new ZipFile(zip); } else { zf = new ZipFile(zip, charset); } Enumeration<? extends ZipEntry> en = zf.entries(); while (en.hasMoreElements()) { ZipEntry e = (ZipEntry) en.nextElement(); InputStream is = zf.getInputStream(e); try { action.process(is, e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + "' with action " + action, ze); } catch (ZipBreakException ex) { break; } finally { IOUtils.closeQuietly(is); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP file and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, String[], ZipInfoCallback) */ public static void iterate(File zip, String[] entryNames, ZipEntryCallback action) { iterate(zip, entryNames, action, null); } /** * Reads the given ZIP file and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * @param charset * charset used to process the zip file * * @see ZipEntryCallback * @see #iterate(File, String[], ZipInfoCallback) */ public static void iterate(File zip, String[] entryNames, ZipEntryCallback action, Charset charset) { ZipFile zf = null; try { if (charset == null) { zf = new ZipFile(zip); } else { zf = new ZipFile(zip, charset); } for (int i = 0; i < entryNames.length; i++) { ZipEntry e = zf.getEntry(entryNames[i]); if (e == null) { continue; } InputStream is = zf.getInputStream(e); try { action.process(is, e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } finally { IOUtils.closeQuietly(is); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Scans the given ZIP file and executes the given action for each entry. * <p> * Only the meta-data without the actual data is read. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @see ZipInfoCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(File zip, ZipInfoCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); Enumeration<? extends ZipEntry> en = zf.entries(); while (en.hasMoreElements()) { ZipEntry e = (ZipEntry) en.nextElement(); try { action.process(e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Scans the given ZIP file and executes the given action for each given entry. * <p> * Only the meta-data without the actual data is read. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipInfoCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(File zip, String[] entryNames, ZipInfoCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); for (int i = 0; i < entryNames.length; i++) { ZipEntry e = zf.getEntry(entryNames[i]); if (e == null) { continue; } try { action.process(e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP stream and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param is * input ZIP stream (it will not be closed automatically). * @param action * action to be called for each entry. * @param charset * charset to process entries in * * @see ZipEntryCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(InputStream is, ZipEntryCallback action, Charset charset) { try { ZipInputStream in = null; try { in = newCloseShieldZipInputStream(is, charset); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { try { action.process(in, entry); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + entry.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * See {@link #iterate(InputStream, ZipEntryCallback, Charset)}. This method * is a shorthand for a version where no Charset is specified. * * @param is * input ZIP stream (it will not be closed automatically). * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(InputStream is, ZipEntryCallback action) { iterate(is, action, null); } /** * Reads the given ZIP stream and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param is * input ZIP stream (it will not be closed automatically). * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * @param charset * charset to process entries in * * @see ZipEntryCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(InputStream is, String[] entryNames, ZipEntryCallback action, Charset charset) { Set<String> namesSet = new HashSet<String>(); for (int i = 0; i < entryNames.length; i++) { namesSet.add(entryNames[i]); } try { ZipInputStream in = null; try { in = newCloseShieldZipInputStream(is, charset); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (!namesSet.contains(entry.getName())) { // skip the unnecessary entry continue; } try { action.process(in, entry); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + entry.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * See @link{ {@link #iterate(InputStream, ZipEntryCallback, Charset)}. It is a * shorthand where no Charset is specified. * * @param is * input ZIP stream (it will not be closed automatically). * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(InputStream is, String[] entryNames, ZipEntryCallback action) { iterate(is, entryNames, action, null); } /** * Creates a new {@link ZipInputStream} based on the given {@link InputStream}. It will be buffered and close-shielded. * Closing the result stream flushes the buffers and frees up resources of the {@link ZipInputStream}. However the source stream itself remains open. */ private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) { InputStream in = new BufferedInputStream(new CloseShieldInputStream(is)); if (charset == null) { return new ZipInputStream(in); } return ZipFileUtil.createZipInputStream(in, charset); } /** * Reads the given ZIP file and executes the given action for a single entry. * * @param zip * input ZIP file. * @param name * entry name. * @param action * action to be called for this entry. * @return <code>true</code> if the entry was found, <code>false</code> if the * entry was not found. * * @see ZipEntryCallback */ public static boolean handle(File zip, String name, ZipEntryCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); ZipEntry ze = zf.getEntry(name); if (ze == null) { return false; // entry not found } InputStream in = new BufferedInputStream(zf.getInputStream(ze)); try { action.process(in, ze); } finally { IOUtils.closeQuietly(in); } return true; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP stream and executes the given action for a single * entry. * * @param is * input ZIP stream (it will not be closed automatically). * @param name * entry name. * @param action * action to be called for this entry. * @return <code>true</code> if the entry was found, <code>false</code> if the * entry was not found. * * @see ZipEntryCallback */ public static boolean handle(InputStream is, String name, ZipEntryCallback action) { SingleZipEntryCallback helper = new SingleZipEntryCallback(name, action); iterate(is, helper); return helper.found(); } /** * ZipEntryCallback which is only applied to single entry. * * @author Rein Raudjärv */ private static class SingleZipEntryCallback implements ZipEntryCallback { private final String name; private final ZipEntryCallback action; private boolean found; public SingleZipEntryCallback(String name, ZipEntryCallback action) { this.name = name; this.action = action; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (name.equals(zipEntry.getName())) { found = true; action.process(in, zipEntry); } } public boolean found() { return found; } } /* Extracting whole ZIP files. */ /** * Unpacks a ZIP file to the given directory. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unpack(File zip, final File outputDir) { unpack(zip, outputDir, IdentityNameMapper.INSTANCE); } /** * Unpacks a ZIP file to the given directory using a specific Charset * for the input file. * * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * * @param charset * charset used to unpack the zip file */ public static void unpack(File zip, final File outputDir, Charset charset) { unpack(zip, outputDir, IdentityNameMapper.INSTANCE, charset); } /** * Unpacks a ZIP file to the given directory. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. * @param charset * charset used to process the zip file */ public static void unpack(File zip, File outputDir, NameMapper mapper, Charset charset) { log.debug("Extracting '{}' into '{}'.", zip, outputDir); iterate(zip, new Unpacker(outputDir, mapper), charset); } /** * Unpacks a ZIP file to the given directory using a specific Charset * for the input file. * * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unpack(File zip, File outputDir, NameMapper mapper) { log.debug("Extracting '{}' into '{}'.", zip, outputDir); iterate(zip, new Unpacker(outputDir, mapper)); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unwrap(File zip, final File outputDir) { unwrap(zip, outputDir, IdentityNameMapper.INSTANCE); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unwrap(File zip, File outputDir, NameMapper mapper) { log.debug("Unwrapping '{}' into '{}'.", zip, outputDir); iterate(zip, new Unwraper(outputDir, mapper)); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unpack(InputStream is, File outputDir) { unpack(is, outputDir, IdentityNameMapper.INSTANCE, null); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param charset * charset used to process the zip stream */ public static void unpack(InputStream is, File outputDir, Charset charset) { unpack(is, outputDir, IdentityNameMapper.INSTANCE, charset); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unpack(InputStream is, File outputDir, NameMapper mapper) { unpack(is, outputDir, mapper, null); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. * @param charset * charset to use when unpacking the stream */ public static void unpack(InputStream is, File outputDir, NameMapper mapper, Charset charset) { log.debug("Extracting {} into '{}'.", is, outputDir); iterate(is, new Unpacker(outputDir, mapper), charset); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unwrap(InputStream is, File outputDir) { unwrap(is, outputDir, IdentityNameMapper.INSTANCE); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unwrap(InputStream is, File outputDir, NameMapper mapper) { log.debug("Unwrapping {} into '{}'.", is, outputDir); iterate(is, new Unwraper(outputDir, mapper)); } /** * Unpacks each ZIP entry. * * @author Rein Raudjärv */ private static class Unpacker implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; public Unpacker(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String name = mapper.map(zipEntry.getName()); if (name != null) { File file = new File(outputDir, name); /* If we see the relative traversal string of ".." we need to make sure * that the outputdir + name doesn't leave the outputdir. See * DirectoryTraversalMaliciousTest for details. */ if (name.indexOf("..") != -1 && !file.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) { throw new ZipException("The file "+name+" is trying to leave the target output directory of "+outputDir+". Ignoring this file."); } if (zipEntry.isDirectory()) { FileUtils.forceMkdir(file); } else { FileUtils.forceMkdir(file.getParentFile()); if (log.isDebugEnabled() && file.exists()) { log.debug("Overwriting file '{}'.", zipEntry.getName()); } FileUtils.copy(in, file); } ZTFilePermissions permissions = ZipEntryUtil.getZTFilePermissions(zipEntry); if (permissions != null) { ZTFilePermissionsUtil.getDefaultStategy().setPermissions(file, permissions); } } } } /** * Unpacks each ZIP entries. Presumes they are packed with the backslash separator. * Some archives can have this problem if they are created with some software * that is not following the ZIP specification. * * @since zt-zip 1.9 */ public static class BackslashUnpacker implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; public BackslashUnpacker(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public BackslashUnpacker(File outputDir) { this(outputDir, IdentityNameMapper.INSTANCE); } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String name = mapper.map(zipEntry.getName()); if (name != null) { /** * We assume that EVERY backslash will denote a directory * separator. Also such broken archives don't have entries that * are just directories. Everything is a file. See the example * * Archive: backSlashTest.zip * testing: testDirectory\testfileInTestDirectory.txt OK * testing: testDirectory\testSubdirectory\testFileInTestSubdirectory.txt OK * No errors detected in compressed data of backSlashTest.zip. */ if (name.indexOf('\\') != -1) { File parentDirectory = outputDir; String[] dirs = name.split("\\\\"); // lets create all the directories and the last entry is the file as EVERY entry is a file for (int i = 0; i < dirs.length - 1; i++) { File file = new File(parentDirectory, dirs[i]); if (!file.exists()) { FileUtils.forceMkdir(file); } parentDirectory = file; } File destFile = new File(parentDirectory, dirs[dirs.length - 1]); /* If we see the relative traversal string of ".." we need to make sure * that the outputdir + name doesn't leave the outputdir. See * DirectoryTraversalMaliciousTest for details. */ if (name.indexOf("..") != -1 && !destFile.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) { throw new ZipException("The file "+name+" is trying to leave the target output directory of "+outputDir+". Ignoring this file."); } FileUtils.copy(in, destFile); } // it could be that there are just top level files that the unpacker is used for else { File destFile = new File(outputDir, name); /* If we see the relative traversal string of ".." we need to make sure * that the outputdir + name doesn't leave the outputdir. See * DirectoryTraversalMaliciousTest for details. */ if (name.indexOf("..") != -1 && !destFile.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) { throw new ZipException("The file "+name+" is trying to leave the target output directory of "+outputDir+". Ignoring this file."); } FileUtils.copy(in, destFile); } } } } /** * Unwraps entries excluding a single parent dir. If there are multiple roots * ZipException is thrown. * * @author Oleg Shelajev */ private static class Unwraper implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; private String rootDir; public Unwraper(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String root = getRootName(zipEntry.getName()); if (rootDir == null) { rootDir = root; } else if (!rootDir.equals(root)) { throw new ZipException("Unwrapping with multiple roots is not supported, roots: " + rootDir + ", " + root); } String name = mapper.map(getUnrootedName(root, zipEntry.getName())); if (name != null) { File file = new File(outputDir, name); /* If we see the relative traversal string of ".." we need to make sure * that the outputdir + name doesn't leave the outputdir. See * DirectoryTraversalMaliciousTest for details. */ if (name.indexOf("..") != -1 && !file.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) { throw new ZipException("The file "+name+" is trying to leave the target output directory of "+outputDir+". Ignoring this file."); } if (zipEntry.isDirectory()) { FileUtils.forceMkdir(file); } else { FileUtils.forceMkdir(file.getParentFile()); if (log.isDebugEnabled() && file.exists()) { log.debug("Overwriting file '{}'.", zipEntry.getName()); } FileUtils.copy(in, file); } } } private String getUnrootedName(String root, String name) { return name.substring(root.length()); } private String getRootName(final String name) { String newName = name.substring(FilenameUtils.getPrefixLength(name)); int idx = newName.indexOf(PATH_SEPARATOR); if (idx < 0) { throw new ZipException("Entry " + newName + " from the root of the zip is not supported"); } return newName.substring(0, newName.indexOf(PATH_SEPARATOR)); } } /** * Unpacks a ZIP file to its own location. * <p> * The ZIP file will be first renamed (using a temporary name). After the * extraction it will be deleted. * * @param zip * input ZIP file as well as the target directory. * * @see #unpack(File, File) */ public static void explode(File zip) { try { // Find a new unique name is the same directory File tempFile = FileUtils.getTempFileFor(zip); // Rename the archive FileUtils.moveFile(zip, tempFile); // Unpack it unpack(tempFile, zip); // Delete the archive if (!tempFile.delete()) { throw new IOException("Unable to delete file: " + tempFile); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /* Compressing single entries to ZIP files. */ /** * Compresses the given file into a ZIP file with single entry. * * @param file file to be compressed. * @return ZIP file created. */ public static byte[] packEntry(File file) { log.trace("Compressing '{}' into a ZIP file with single entry.", file); ByteArrayOutputStream result = new ByteArrayOutputStream(); try { ZipOutputStream out = new ZipOutputStream(result); ZipEntry entry = ZipEntryUtil.fromFile(file.getName(), file); InputStream in = new BufferedInputStream(new FileInputStream(file)); try { ZipEntryUtil.addEntry(entry, in, out); } finally { IOUtils.closeQuietly(in); } out.close(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } return result.toByteArray(); } /* Compressing ZIP files. */ /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param rootDir * root directory. * @param zip * ZIP file that will be created or overwritten. */ public static void pack(File rootDir, File zip) { pack(rootDir, zip, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param rootDir * root directory. * @param zip * ZIP file that will be created or overwritten. * @param compressionLevel * compression level */ public static void pack(File rootDir, File zip, int compressionLevel) { pack(rootDir, zip, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param sourceDir * root directory. * @param targetZipFile * ZIP file that will be created or overwritten. * @param preserveRoot * true if the resulted archive should have the top directory entry */ public static void pack(final File sourceDir, final File targetZipFile, final boolean preserveRoot) { if (preserveRoot) { final String parentName = sourceDir.getName(); pack(sourceDir, targetZipFile, new NameMapper() { public String map(String name) { return parentName + PATH_SEPARATOR + name; } }); } else { pack(sourceDir, targetZipFile); } } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. */ public static void packEntry(File fileToPack, File destZipFile) { packEntry(fileToPack, destZipFile, IdentityNameMapper.INSTANCE); } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param fileName * the name for the file inside the archive */ public static void packEntry(File fileToPack, File destZipFile, final String fileName) { packEntry(fileToPack, destZipFile, new NameMapper() { public String map(String name) { return fileName; } }); } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void packEntry(File fileToPack, File destZipFile, NameMapper mapper) { packEntries(new File[] { fileToPack }, destZipFile, mapper); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. */ public static void packEntries(File[] filesToPack, File destZipFile) { packEntries(filesToPack, destZipFile, IdentityNameMapper.INSTANCE); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper) { packEntries(filesToPack, destZipFile, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param compressionLevel * ZIP file compression level (speed versus filesize), e.g. <code>Deflater.NO_COMPRESSION</code>, <code>Deflater.BEST_SPEED</code>, or * <code>Deflater.BEST_COMPRESSION</code> */ public static void packEntries(File[] filesToPack, File destZipFile, int compressionLevel) { packEntries(filesToPack, destZipFile, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. * @param compressionLevel * ZIP file compression level (speed versus filesize), e.g. <code>Deflater.NO_COMPRESSION</code>, <code>Deflater.BEST_SPEED</code>, or * <code>Deflater.BEST_COMPRESSION</code> */ public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile); ZipOutputStream out = null; FileOutputStream fos = null; try { fos = new FileOutputStream(destZipFile); out = new ZipOutputStream(new BufferedOutputStream(fos)); out.setLevel(compressionLevel); for (int i = 0; i < filesToPack.length; i++) { File fileToPack = filesToPack[i]; ZipEntry zipEntry = ZipEntryUtil.fromFile(mapper.map(fileToPack.getName()), fileToPack); out.putNextEntry(zipEntry); FileUtils.copy(fileToPack, out); out.closeEntry(); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fos); } } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param sourceDir * root directory. * @param targetZip * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void pack(File sourceDir, File targetZip, NameMapper mapper) { pack(sourceDir, targetZip, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param sourceDir * root directory. * @param targetZip * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. * @param compressionLevel * compression level */ public static void pack(File sourceDir, File targetZip, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into '{}'.", sourceDir, targetZip); if (!sourceDir.exists()) { throw new ZipException("Given file '" + sourceDir + "' doesn't exist!"); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZip))); out.setLevel(compressionLevel); pack(sourceDir, out, mapper, "", true); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os) { pack(sourceDir, os, IdentityNameMapper.INSTANCE, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param compressionLevel * compression level * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, int compressionLevel) { pack(sourceDir, os, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param mapper * call-back for renaming the entries. * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, NameMapper mapper) { pack(sourceDir, os, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param mapper * call-back for renaming the entries. * @param compressionLevel * compression level * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into a stream.", sourceDir); if (!sourceDir.exists()) { throw new ZipException("Given file '" + sourceDir + "' doesn't exist!"); } ZipOutputStream out = null; IOException error = null; try { out = new ZipOutputStream(new BufferedOutputStream(os)); out.setLevel(compressionLevel); pack(sourceDir, out, mapper, "", true); } catch (IOException e) { error = e; } finally { if (out != null && error == null) { try { out.finish(); out.flush(); } catch (IOException e) { error = e; } } } if (error != null) { throw ZipExceptionUtil.rethrow(error); } } /** * Compresses the given directory and all its sub-directories into a ZIP file. * * @param dir * root directory. * @param out * ZIP output stream. * @param mapper * call-back for renaming the entries. * @param pathPrefix * prefix to be used for the entries. * @param mustHaveChildren * if true, but directory to pack doesn't have any files, throw an exception. */ private static void pack(File dir, ZipOutputStream out, NameMapper mapper, String pathPrefix, boolean mustHaveChildren) throws IOException { String[] filenames = dir.list(); if (filenames == null) { if (!dir.exists()) { throw new ZipException("Given file '" + dir + "' doesn't exist!"); } throw new IOException("Given file is not a directory '" + dir + "'"); } if (mustHaveChildren && filenames.length == 0) { throw new ZipException("Given directory '" + dir + "' doesn't contain any files!"); } for (int i = 0; i < filenames.length; i++) { String filename = filenames[i]; File file = new File(dir, filename); boolean isDir = file.isDirectory(); String path = pathPrefix + file.getName(); // NOSONAR if (isDir) { path += PATH_SEPARATOR; // NOSONAR } // Create a ZIP entry String name = mapper.map(path); if (name != null) { ZipEntry zipEntry = ZipEntryUtil.fromFile(name, file); out.putNextEntry(zipEntry); // Copy the file content if (!isDir) { FileUtils.copy(file, out); } out.closeEntry(); } // Traverse the directory if (isDir) { pack(file, out, mapper, path, false); } } } /** * Repacks a provided ZIP file into a new ZIP with a given compression level. * <p> * * @param srcZip * source ZIP file. * @param dstZip * destination ZIP file. * @param compressionLevel * compression level. */ public static void repack(File srcZip, File dstZip, int compressionLevel) { log.debug("Repacking '{}' into '{}'.", srcZip, dstZip); RepackZipEntryCallback callback = new RepackZipEntryCallback(dstZip, compressionLevel); try { iterate(srcZip, callback); } finally { callback.closeStream(); } } /** * Repacks a provided ZIP input stream into a ZIP file with a given compression level. * <p> * * @param is * ZIP input stream. * @param dstZip * destination ZIP file. * @param compressionLevel * compression level. */ public static void repack(InputStream is, File dstZip, int compressionLevel) { log.debug("Repacking from input stream into '{}'.", dstZip); RepackZipEntryCallback callback = new RepackZipEntryCallback(dstZip, compressionLevel); try { iterate(is, callback); } finally { callback.closeStream(); } } /** * Repacks a provided ZIP file and replaces old file with the new one. * <p> * * @param zip * source ZIP file to be repacked and replaced. * @param compressionLevel * compression level. */ public static void repack(File zip, int compressionLevel) { try { File tmpZip = FileUtils.getTempFileFor(zip); repack(zip, tmpZip, compressionLevel); // Delete original zip if (!zip.delete()) { throw new IOException("Unable to delete the file: " + zip); } // Rename the archive FileUtils.moveFile(tmpZip, zip); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * RepackZipEntryCallback used in repacking methods. * * @author Pavel Grigorenko */ private static final class RepackZipEntryCallback implements ZipEntryCallback { private ZipOutputStream out; private RepackZipEntryCallback(File dstZip, int compressionLevel) { try { this.out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dstZip))); this.out.setLevel(compressionLevel); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } public void process(InputStream in, ZipEntry zipEntry) throws IOException { ZipEntryUtil.copyEntry(zipEntry, in, out); } private void closeStream() { IOUtils.closeQuietly(out); } } /** * Compresses a given directory in its own location. * <p> * A ZIP file will be first created with a temporary name. After the * compressing the directory will be deleted and the ZIP file will be renamed * as the original directory. * * @param dir * input directory as well as the target ZIP file. * * @see #pack(File, File) */ public static void unexplode(File dir) { unexplode(dir, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses a given directory in its own location. * <p> * A ZIP file will be first created with a temporary name. After the * compressing the directory will be deleted and the ZIP file will be renamed * as the original directory. * * @param dir * input directory as well as the target ZIP file. * @param compressionLevel * compression level * * @see #pack(File, File) */ public static void unexplode(File dir, int compressionLevel) { try { // Find a new unique name is the same directory File zip = FileUtils.getTempFileFor(dir); // Pack it pack(dir, zip, compressionLevel); // Delete the directory FileUtils.deleteDirectory(dir); // Rename the archive FileUtils.moveFile(zip, dir); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compresses the given entries into an output stream. * * @param entries * ZIP entries added. * @param os * output stream for the new ZIP (does not have to be buffered) * * @since 1.9 */ public static void pack(ZipEntrySource[] entries, OutputStream os) { if (log.isDebugEnabled()) { log.debug("Creating stream from {}.", Arrays.asList(entries)); } pack(entries, os, false); } private static void pack(ZipEntrySource[] entries, OutputStream os, boolean closeStream) { try { ZipOutputStream out = new ZipOutputStream(os); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.flush(); out.finish(); if (closeStream) { out.close(); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compresses the given entries into a new ZIP file. * * @param entries * ZIP entries added. * @param zip * new ZIP file created. */ public static void pack(ZipEntrySource[] entries, File zip) { if (log.isDebugEnabled()) { log.debug("Creating '{}' from {}.", zip, Arrays.asList(entries)); } OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(zip)); pack(entries, out, true); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry to be added. * @param destZip * new ZIP file created. */ public static void addEntry(File zip, String path, File file, File destZip) { addEntry(zip, new FileSource(path, file), destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry to be added. */ public static void addEntry(final File zip, final String path, final File file) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, file, tmpFile); return true; } }); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. */ public static void addEntry(File zip, String path, byte[] bytes, File destZip) { addEntry(zip, new ByteSource(path, bytes), destZip); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). */ public static void addEntry(File zip, String path, byte[] bytes, File destZip, final int compressionMethod) { addEntry(zip, new ByteSource(path, bytes, compressionMethod), destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). */ public static void addEntry(final File zip, final String path, final byte[] bytes) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, bytes, tmpFile); return true; } }); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). */ public static void addEntry(final File zip, final String path, final byte[] bytes, final int compressionMethod) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, bytes, tmpFile, compressionMethod); return true; } }); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry appended. * @param destZip * new ZIP file created. */ public static void addEntry(File zip, ZipEntrySource entry, File destZip) { addEntries(zip, new ZipEntrySource[] { entry }, destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry appended. */ public static void addEntry(final File zip, final ZipEntrySource entry) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, entry, tmpFile); return true; } }); } /** * Copies an existing ZIP file and appends it with new entries. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. * @param destZip * new ZIP file created. */ public static void addEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and adding " + Arrays.asList(entries) + "."); } OutputStream destOut = null; try { destOut = new BufferedOutputStream(new FileOutputStream(destZip)); addEntries(zip, entries, destOut); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(destOut); } } /** * Copies an existing ZIP file and appends it with new entries. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. * @param destOut * new ZIP destination output stream */ public static void addEntries(File zip, ZipEntrySource[] entries, OutputStream destOut) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to a stream and adding " + Arrays.asList(entries) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(destOut); copyEntries(zip, out); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.finish(); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Copies an existing ZIP file and appends it with new entries. * * @param is * an existing ZIP input stream. * @param entries * new ZIP entries appended. * @param destOut * new ZIP destination output stream * * @since 1.9 */ public static void addEntries(InputStream is, ZipEntrySource[] entries, OutputStream destOut) { if (log.isDebugEnabled()) { log.debug("Copying input stream to an output stream and adding " + Arrays.asList(entries) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(destOut); copyEntries(is, out); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.finish(); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Changes a zip file it with with new entries. in-place. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. */ public static void addEntries(final File zip, final ZipEntrySource[] entries) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntries(zip, entries, tmpFile); return true; } }); } /** * Copies an existing ZIP file and removes entry with a given path. * * @param zip * an existing ZIP file (only read) * @param path * path of the entry to remove * @param destZip * new ZIP file created. * @since 1.7 */ public static void removeEntry(File zip, String path, File destZip) { removeEntries(zip, new String[] { path }, destZip); } /** * Changes an existing ZIP file: removes entry with a given path. * * @param zip * an existing ZIP file * @param path * path of the entry to remove * @since 1.7 */ public static void removeEntry(final File zip, final String path) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { removeEntry(zip, path, tmpFile); return true; } }); } /** * Copies an existing ZIP file and removes entries with given paths. * * @param zip * an existing ZIP file (only read) * @param paths * paths of the entries to remove * @param destZip * new ZIP file created. * @since 1.7 */ public static void removeEntries(File zip, String[] paths, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and removing paths " + Arrays.asList(paths) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths))); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Changes an existing ZIP file: removes entries with given paths. * * @param zip * an existing ZIP file * @param paths * paths of the entries to remove * @since 1.7 */ public static void removeEntries(final File zip, final String[] paths) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { removeEntries(zip, paths, tmpFile); return true; } }); } /** * Copies all entries from one ZIP file to another. * * @param zip * source ZIP file. * @param out * target ZIP stream. */ private static void copyEntries(File zip, final ZipOutputStream out) { // this one doesn't call copyEntries with ignoredEntries, because that has poorer performance final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * Copies all entries from one ZIP stream to another. * * @param is * source stream (contains ZIP file). * @param out * target ZIP stream. */ private static void copyEntries(InputStream is, final ZipOutputStream out) { // this one doesn't call copyEntries with ignoredEntries, because that has poorer performance final Set<String> names = new HashSet<String>(); iterate(is, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * Copies all entries from one ZIP file to another, ignoring entries with path in ignoredEntries * * @param zip * source ZIP file. * @param out * target ZIP stream. * @param ignoredEntries * paths of entries not to copy */ private static void copyEntries(File zip, final ZipOutputStream out, final Set<String> ignoredEntries) { final Set<String> names = new HashSet<String>(); final Set<String> dirNames = filterDirEntries(zip, ignoredEntries); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (ignoredEntries.contains(entryName)) { return; } for (String dirName : dirNames) { if (entryName.startsWith(dirName)) { return; } } if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * * @param zip * zip file to traverse * @param names * names of entries to filter dirs from * @return Set<String> names of entries that are dirs. * */ static Set<String> filterDirEntries(File zip, Collection<String> names) { Set<String> dirs = new HashSet<String>(); if (zip == null) { return dirs; } ZipFile zf = null; try { zf = new ZipFile(zip); for (String entryName : names) { ZipEntry entry = zf.getEntry(entryName); if (entry != null) { if (entry.isDirectory()) { dirs.add(entry.getName()); } else if (zf.getInputStream(entry) == null) { // no input stream means that this is a dir. dirs.add(entry.getName() + PATH_SEPARATOR); } } } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } return dirs; } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, String path, File file, File destZip) { return replaceEntry(zip, new FileSource(path, file), destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param file * new entry. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final File file) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new FileSource(path, file), tmpFile); } }); } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, String path, byte[] bytes, File destZip) { return replaceEntry(zip, new ByteSource(path, bytes), destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final byte[] bytes) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new ByteSource(path, bytes), tmpFile); } }); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final byte[] bytes, final int compressionMethod) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new ByteSource(path, bytes, compressionMethod), tmpFile); } }); } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, ZipEntrySource entry, File destZip) { return replaceEntries(zip, new ZipEntrySource[] { entry }, destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param entry * new ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final ZipEntrySource entry) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, entry, tmpFile); } }); } /** * Copies an existing ZIP file and replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries to be replaced with. * @param destZip * new ZIP file created. * @return <code>true</code> if at least one entry was replaced. */ public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + "."); } final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries); final int entryCount = entryByPath.size(); try { final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName()); if (entry != null) { addEntry(entry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } }); } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } return entryByPath.size() < entryCount; } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param entries * new ZIP entries to be replaced with. * @return <code>true</code> if at least one entry was replaced. */ public static boolean replaceEntries(final File zip, final ZipEntrySource[] entries) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntries(zip, entries, tmpFile); } }); } /** * Copies an existing ZIP file and adds/replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entries to be replaced or added. * @param destZip * new ZIP file created. */ public static void addOrReplaceEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and adding/replacing entries " + Arrays.asList(entries) + "."); } final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries); try { final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { // Copy and replace entries final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName()); if (entry != null) { addEntry(entry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } }); // Add new entries for (ZipEntrySource zipEntrySource : entryByPath.values()) { addEntry(zipEntrySource, out); } } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Changes a ZIP file: adds/replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entries to be replaced or added. */ public static void addOrReplaceEntries(final File zip, final ZipEntrySource[] entries) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addOrReplaceEntries(zip, entries, tmpFile); return true; } }); } /** * @return given entries indexed by path. */ static Map<String, ZipEntrySource> entriesByPath(ZipEntrySource... entries) { Map<String, ZipEntrySource> result = new HashMap<String, ZipEntrySource>(); for (int i = 0; i < entries.length; i++) { ZipEntrySource source = entries[i]; result.put(source.getPath(), source); } return result; } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @param destZip * new ZIP file created. * @throws IllegalArgumentException if the destination is the same as the location * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(File zip, String path, ZipEntryTransformer transformer, File destZip) { if(zip.equals(destZip)){throw new IllegalArgumentException("Input (" +zip.getAbsolutePath()+ ") is the same as the destination!" + "Please use the transformEntry method without destination for in-place transformation." );} return transformEntry(zip, new ZipEntryTransformerEntry(path, transformer), destZip); } /** * Changes an existing ZIP file: transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(final File zip, final String path, final ZipEntryTransformer transformer) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntry(zip, path, transformer, tmpFile); } }); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * transformer for a ZIP entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(File zip, ZipEntryTransformerEntry entry, File destZip) { return transformEntries(zip, new ZipEntryTransformerEntry[] { entry }, destZip); } /** * Changes an existing ZIP file: transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * transformer for a ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(final File zip, final ZipEntryTransformerEntry entry) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntry(zip, entry, tmpFile); } }); } /** * Copies an existing ZIP file and transforms the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entry transformers. * @param destZip * new ZIP file created. * @return <code>true</code> if at least one entry was replaced. */ public static boolean transformEntries(File zip, ZipEntryTransformerEntry[] entries, File destZip) { if (log.isDebugEnabled()) log.debug("Copying '" + zip + "' to '" + destZip + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(zip, action); return action.found(); } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Changes an existing ZIP file: transforms a given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entry transformers. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntries(final File zip, final ZipEntryTransformerEntry[] entries) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntries(zip, entries, tmpFile); } }); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param is * a ZIP input stream. * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @param os * a ZIP output stream. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(InputStream is, String path, ZipEntryTransformer transformer, OutputStream os) { return transformEntry(is, new ZipEntryTransformerEntry(path, transformer), os); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param is * a ZIP input stream. * @param entry * transformer for a ZIP entry. * @param os * a ZIP output stream. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); } /** * Copies an existing ZIP file and transforms the given entries in it. * * @param is * a ZIP input stream. * @param entries * ZIP entry transformers. * @param os * a ZIP output stream. * @return <code>true</code> if at least one entry was replaced. */ public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) { if (log.isDebugEnabled()) log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(os); TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(is, action); // Finishes writing the contents of the ZIP output stream without closing // the underlying stream. out.finish(); return action.found(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } private static class TransformerZipEntryCallback implements ZipEntryCallback { private final Map<String, ZipEntryTransformer> entryByPath; private final int entryCount; private final ZipOutputStream out; private final Set<String> names = new HashSet<String>(); public TransformerZipEntryCallback(List<ZipEntryTransformerEntry> entries, ZipOutputStream out) { entryByPath = transformersByPath(entries); entryCount = entryByPath.size(); this.out = out; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntryTransformer entry = (ZipEntryTransformer) entryByPath.remove(zipEntry.getName()); if (entry != null) { entry.transform(in, zipEntry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } /** * @return <code>true</code> if at least one entry was replaced. */ public boolean found() { return entryByPath.size() < entryCount; } } /** * @return transformers by path. */ static Map<String, ZipEntryTransformer> transformersByPath(List<ZipEntryTransformerEntry> entries) { Map<String, ZipEntryTransformer> result = new HashMap<String, ZipEntryTransformer>(); for (ZipEntryTransformerEntry entry : entries) { result.put(entry.getPath(), entry.getTransformer()); } return result; } /** * Adds a given ZIP entry to a ZIP file. * * @param entry * new ZIP entry. * @param out * target ZIP stream. */ private static void addEntry(ZipEntrySource entry, ZipOutputStream out) throws IOException { out.putNextEntry(entry.getEntry()); InputStream in = entry.getInputStream(); if (in != null) { try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } } out.closeEntry(); } /* Comparing two ZIP files. */ /** * Compares two ZIP files and returns <code>true</code> if they contain same * entries. * <p> * First the two files are compared byte-by-byte. If a difference is found the * corresponding entries of both ZIP files are compared. Thus if same contents * is packed differently the two archives may still be the same. * </p> * <p> * Two archives are considered the same if * <ol> * <li>they contain same number of entries,</li> * <li>for each entry in the first archive there exists an entry with the same * in the second archive</li> * <li>for each entry in the first archive and the entry with the same name in * the second archive * <ol> * <li>both are either directories or files,</li> * <li>both have the same size,</li> * <li>both have the same CRC,</li> * <li>both have the same contents (compared byte-by-byte).</li> * </ol> * </li> * </ol> * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @return <code>true</code> if the two ZIP files contain same entries, * <code>false</code> if a difference was found or an error occurred * during the comparison. */ public static boolean archiveEquals(File f1, File f2) { try { // Check the files byte-by-byte if (FileUtils.contentEquals(f1, f2)) { return true; } log.debug("Comparing archives '{}' and '{}'...", f1, f2); long start = System.currentTimeMillis(); boolean result = archiveEqualsInternal(f1, f2); long time = System.currentTimeMillis() - start; if (time > 0) { log.debug("Archives compared in " + time + " ms."); } return result; } catch (Exception e) { log.debug("Could not compare '" + f1 + "' and '" + f2 + "':", e); return false; } } private static boolean archiveEqualsInternal(File f1, File f2) throws IOException { ZipFile zf1 = null; ZipFile zf2 = null; try { zf1 = new ZipFile(f1); zf2 = new ZipFile(f2); // Check the number of entries if (zf1.size() != zf2.size()) { log.debug("Number of entries changed (" + zf1.size() + " vs " + zf2.size() + ")."); return false; } /* * As there are same number of entries in both archives we can traverse * all entries of one of the archives and get the corresponding entries * from the other archive. * * If a corresponding entry is missing from the second archive the * archives are different and we finish the comparison. * * We guarantee that no entry of the second archive is skipped as there * are same number of unique entries in both archives. */ Enumeration<? extends ZipEntry> en = zf1.entries(); while (en.hasMoreElements()) { ZipEntry e1 = (ZipEntry) en.nextElement(); String path = e1.getName(); ZipEntry e2 = zf2.getEntry(path); // Check meta data if (!metaDataEquals(path, e1, e2)) { return false; } // Check the content InputStream is1 = null; InputStream is2 = null; try { is1 = zf1.getInputStream(e1); is2 = zf2.getInputStream(e2); if (!IOUtils.contentEquals(is1, is2)) { log.debug("Entry '{}' content changed.", path); return false; } } finally { IOUtils.closeQuietly(is1); IOUtils.closeQuietly(is2); } } } finally { closeQuietly(zf1); closeQuietly(zf2); } log.debug("Archives are the same."); return true; } /** * Compares meta-data of two ZIP entries. * <p> * Two entries are considered the same if * <ol> * <li>both entries exist,</li> * <li>both entries are either directories or files,</li> * <li>both entries have the same size,</li> * <li>both entries have the same CRC.</li> * </ol> * * @param path * name of the entries. * @param e1 * first entry (required). * @param e2 * second entry (may be <code>null</code>). * @return <code>true</code> if no difference was found. */ private static boolean metaDataEquals(String path, ZipEntry e1, ZipEntry e2) throws IOException { // Check if the same entry exists in the second archive if (e2 == null) { log.debug("Entry '{}' removed.", path); return false; } // Check the directory flag if (e1.isDirectory()) { if (e2.isDirectory()) { return true; // Let's skip the directory as there is nothing to compare } else { log.debug("Entry '{}' not a directory any more.", path); return false; } } else if (e2.isDirectory()) { log.debug("Entry '{}' now a directory.", path); return false; } // Check the size long size1 = e1.getSize(); long size2 = e2.getSize(); if (size1 != -1 && size2 != -1 && size1 != size2) { log.debug("Entry '" + path + "' size changed (" + size1 + " vs " + size2 + ")."); return false; } // Check the CRC long crc1 = e1.getCrc(); long crc2 = e2.getCrc(); if (crc1 != -1 && crc2 != -1 && crc1 != crc2) { log.debug("Entry '" + path + "' CRC changed (" + crc1 + " vs " + crc2 + ")."); return false; } // Check the time (ignored, logging only) if (log.isTraceEnabled()) { long time1 = e1.getTime(); long time2 = e2.getTime(); if (time1 != -1 && time2 != -1 && time1 != time2) { log.trace("Entry '" + path + "' time changed (" + new Date(time1) + " vs " + new Date(time2) + ")."); } } return true; } /** * Compares same entry in two ZIP files (byte-by-byte). * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @param path * name of the entry. * @return <code>true</code> if the contents of the entry was same in both ZIP * files. */ public static boolean entryEquals(File f1, File f2, String path) { return entryEquals(f1, f2, path, path); } /** * Compares two ZIP entries (byte-by-byte). . * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ public static boolean entryEquals(File f1, File f2, String path1, String path2) { ZipFile zf1 = null; ZipFile zf2 = null; try { zf1 = new ZipFile(f1); zf2 = new ZipFile(f2); return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf1); closeQuietly(zf2); } } /** * Compares two ZIP entries (byte-by-byte). . * * @param zf1 * first ZIP file. * @param zf2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ public static boolean entryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) { try { return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compares two ZIP entries (byte-by-byte). . * * @param zf1 * first ZIP file. * @param zf2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ private static boolean doEntryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) throws IOException { InputStream is1 = null; InputStream is2 = null; try { ZipEntry e1 = zf1.getEntry(path1); ZipEntry e2 = zf2.getEntry(path2); if (e1 == null && e2 == null) { return true; } if (e1 == null || e2 == null) { return false; } is1 = zf1.getInputStream(e1); is2 = zf2.getInputStream(e2); if (is1 == null && is2 == null) { return true; } if (is1 == null || is2 == null) { return false; } return IOUtils.contentEquals(is1, is2); } finally { IOUtils.closeQuietly(is1); IOUtils.closeQuietly(is2); } } /** * Closes the ZIP file while ignoring any errors. * * @param zf * ZIP file to be closed. */ public static void closeQuietly(ZipFile zf) { try { if (zf != null) { zf.close(); } } catch (IOException e) { } } /** * Simple helper to make inplace operation easier * * @author shelajev */ private abstract static class InPlaceAction { /** * @return true if something has been changed during the action. */ abstract boolean act(File tmpFile); } /** * * This method provides a general infrastructure for in-place operations. * It creates temp file as a destination, then invokes the action on source and destination. * Then it copies the result back into src file. * * @param src - source zip file we want to modify * @param action - action which actually modifies the archives * * @return result of the action */ private static boolean operateInPlace(File src, InPlaceAction action) { File tmp = null; try { tmp = File.createTempFile("zt-zip-tmp", ".zip"); boolean result = action.act(tmp); if (result) { // else nothing changes FileUtils.forceDelete(src); FileUtils.moveFile(tmp, src); } return result; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { FileUtils.deleteQuietly(tmp); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_68_0
crossvul-java_data_bad_4471_0
/* * file: InputStreamHelper.java * author: Jon Iles * copyright: (c) Packwood Software 2016 * date: 06/06/2016 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.common; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipInputStream; /** * Helper methods for dealing with InputStreams. */ public class InputStreamHelper { /** * Copy the data from an InputStream to a temp file. * * @param inputStream data source * @param tempFileSuffix suffix to use for temp file * @return File instance */ public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException { FileOutputStream outputStream = null; try { File file = File.createTempFile("mpxj", tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } } /** * Expands a zip file input stream into a temporary directory. * * @param inputStream zip file input stream * @return File instance representing the temporary directory */ public static File writeZipStreamToTempDir(InputStream inputStream) throws IOException { File dir = FileHelper.createTempDir(); try { processZipStream(dir, inputStream); } catch (ZipException ex) { // Java doesn't support zip files with zero byte entries. // We could use a different library which does handle these zip files, but // I'm reluctant to add new dependencies just for this. Rather than // propagating the error, we'll just stop at this point and see if we // can make sense of anything we have extracted from the zip file so far. // For what it's worth I haven't come across a valid compressed schedule file // which includes zero bytes files. if (!ex.getMessage().equals("only DEFLATED entries can have EXT descriptor")) { throw ex; } } return dir; } /** * Expands a zip file input stream into a temporary directory. * * @param dir temporary directory * @param inputStream zip file input stream */ private static void processZipStream(File dir, InputStream inputStream) throws IOException { ZipInputStream zip = new ZipInputStream(inputStream); while (true) { ZipEntry entry = zip.getNextEntry(); if (entry == null) { break; } File file = new File(dir, entry.getName()); if (entry.isDirectory()) { FileHelper.mkdirsQuietly(file); continue; } File parent = file.getParentFile(); if (parent != null) { FileHelper.mkdirsQuietly(parent); } FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = zip.read(bytes)) >= 0) { fos.write(bytes, 0, length); } fos.close(); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4471_0
crossvul-java_data_good_689_0
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.ResourceUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.isTrue(isValid(path), "Path is not valid"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } private static boolean isValid(final String path) { return !isInvalidPath(path); } private static boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { return true; } if (path.contains(":/")) { String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path); if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) { return true; } } if (path.contains("")) { path = StringUtils.cleanPath(path); if (path.contains("../")) { return true; } } return false; } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @return if exists. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @return the input stream. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @return the url. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @return the resource. * @see spark.utils.StringUtils#applyRelativePath(String, String) */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @return the file name. * @see spark.utils.StringUtils#getFilename(String) */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_689_0
crossvul-java_data_good_1884_2
package eu.hinsch.spring.boot.actuator.logview; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.ui.Model; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; /** * Created by lh on 23/02/15. */ public class LogViewEndpoint implements MvcEndpoint{ private final List<FileProvider> fileProviders; private final Configuration freemarkerConfig; private final String loggingPath; private final List<String> stylesheets; public LogViewEndpoint(String loggingPath, List<String> stylesheets) { this.loggingPath = loggingPath; this.stylesheets = stylesheets; fileProviders = asList(new FileSystemFileProvider(), new ZipArchiveFileProvider(), new TarGzArchiveFileProvider()); freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); } @RequestMapping public void redirect(HttpServletResponse response) throws IOException { response.sendRedirect("log/"); } @RequestMapping("/") @ResponseBody public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { Path currentFolder = loggingPath(base); securityCheck(currentFolder, null); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); } private FileProvider getFileProvider(Path folder) { return fileProviders.stream() .filter(provider -> provider.canHandle(folder)) .findFirst() .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString())); } private String getParent(Path loggingPath) { Path basePath = loggingPath(null); String parent = ""; if (!basePath.toString().equals(loggingPath.toString())) { parent = loggingPath.getParent().toString(); if (parent.startsWith(basePath.toString())) { parent = parent.substring(basePath.toString().length()); } } return parent; } private Path loggingPath(String base) { return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath); } private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) { Comparator<FileEntry> comparator = null; switch (sortBy) { case FILENAME: comparator = (a, b) -> a.getFilename().compareTo(b.getFilename()); break; case SIZE: comparator = (a, b) -> Long.compare(a.getSize(), b.getSize()); break; case MODIFIED: comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis()); break; } List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList()); if (desc) { Collections.reverse(sortedFiles); } return sortedFiles; } @RequestMapping("/view") public void view(@RequestParam String filename, @RequestParam(required = false) String base, @RequestParam(required = false) Integer tailLines, HttpServletResponse response) throws IOException { Path path = loggingPath(base); securityCheck(path, filename); response.setContentType(MediaType.TEXT_PLAIN_VALUE); FileProvider fileProvider = getFileProvider(path); if (tailLines != null) { fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines); } else { fileProvider.streamContent(path, filename, response.getOutputStream()); } } @RequestMapping("/search") public void search(@RequestParam String term, HttpServletResponse response) throws IOException { Path folder = loggingPath(null); List<FileEntry> files = getFileProvider(folder).getFileEntries(folder); List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false); response.setContentType(MediaType.TEXT_PLAIN_VALUE); ServletOutputStream outputStream = response.getOutputStream(); sortedFiles.stream() .filter(file -> file.getFileType().equals(FileType.FILE)) .forEach(file -> searchAndStreamFile(file, term, outputStream)); } private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) { Path folder = loggingPath(null); try { List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename()))) .stream() .filter(line -> line.contains(term)) .map(line -> "[" + fileEntry.getFilename() + "] " + line) .collect(toList()); for (String line : lines) { outputStream.write(line.getBytes()); outputStream.write(System.lineSeparator().getBytes()); } } catch (IOException e) { throw new RuntimeException("error reading file", e); } } private void securityCheck(Path base, String filename) { try { String canonicalLoggingPath = (filename != null ? new File(base.toFile().toString(), filename) : new File(base.toFile().toString())).getCanonicalPath(); String baseCanonicalPath = new File(loggingPath).getCanonicalPath(); String errorMessage = "File " + base.toString() + "/" + filename + " may not be located outside base path " + loggingPath; Assert.isTrue(canonicalLoggingPath.startsWith(baseCanonicalPath), errorMessage); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String getPath() { return "/log"; } @Override public boolean isSensitive() { return true; } @Override public Class<? extends Endpoint> getEndpointType() { return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_1884_2
crossvul-java_data_good_67_1
package org.codehaus.plexus.archiver.zip; import java.io.File; import java.lang.reflect.Method; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector; import org.codehaus.plexus.util.FileUtils; /** * @author Jason van Zyl */ public class ZipUnArchiverTest extends PlexusTestCase { public void testExtractingZipPreservesExecutableFlag() throws Exception { String s = "target/zip-unarchiver-tests"; File testZip = new File( getBasedir(), "src/test/jars/test.zip" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.extract( "", outputDirectory ); File testScript = new File( outputDirectory, "test.sh" ); final Method canExecute; try { canExecute = File.class.getMethod( "canExecute" ); canExecute.invoke( testScript ); assertTrue( (Boolean) canExecute.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } public void testZeroFileModeInZip() throws Exception { String s = "target/zip-unarchiver-filemode-tests"; File testZip = new File( getBasedir(), "src/test/resources/zeroFileMode/foobar.zip" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.setIgnorePermissions( false ); zu.extract( "", outputDirectory ); File testScript = new File( outputDirectory, "foo.txt" ); final Method canRead; try { canRead = File.class.getMethod( "canRead" ); canRead.invoke( testScript ); assertTrue( (Boolean) canRead.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } public void testUnarchiveUtf8() throws Exception { File dest = new File( "target/output/unzip/utf8" ); dest.mkdirs(); final File zipFile = new File( "target/output/unzip/utf8-default.zip" ); final ZipArchiver zipArchiver = getZipArchiver( zipFile ); zipArchiver.addDirectory( new File( "src/test/resources/miscUtf8" ) ); zipArchiver.createArchive(); final ZipUnArchiver unarchiver = getZipUnArchiver( zipFile ); unarchiver.setDestFile( dest ); unarchiver.extract(); assertTrue( new File( dest, "aPi\u00F1ata.txt" ).exists() ); assertTrue( new File( dest, "an\u00FCmlaut.txt" ).exists() ); assertTrue( new File( dest, "\u20acuro.txt" ).exists() ); } private void runUnarchiver( String path, FileSelector[] selectors, boolean[] results ) throws Exception { String s = "target/zip-unarchiver-tests"; File testJar = new File( getBasedir(), "src/test/jars/test.jar" ); File outputDirectory = new File( getBasedir(), s ); ZipUnArchiver zu = getZipUnArchiver( testJar ); zu.setFileSelectors( selectors ); FileUtils.deleteDirectory( outputDirectory ); zu.extract( path, outputDirectory ); File f0 = new File( getBasedir(), s + "/resources/artifactId/test.properties" ); assertEquals( results[0], f0.exists() ); File f1 = new File( getBasedir(), s + "/resources/artifactId/directory/test.properties" ); assertEquals( results[1], f1.exists() ); File f2 = new File( getBasedir(), s + "/META-INF/MANIFEST.MF" ); assertEquals( results[2], f2.exists() ); } private ZipUnArchiver getZipUnArchiver( File testJar ) throws Exception { ZipUnArchiver zu = (ZipUnArchiver) lookup( UnArchiver.ROLE, "zip" ); zu.setSourceFile( testJar ); return zu; } public void testExtractingADirectoryFromAJarFile() throws Exception { runUnarchiver( "resources/artifactId", null, new boolean[] { true, true, false } ); runUnarchiver( "", null, new boolean[] { true, true, true } ); } public void testSelectors() throws Exception { IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); runUnarchiver( "", new FileSelector[] { fileSelector }, new boolean[] { true, true, true } ); fileSelector.setExcludes( new String[] { "**/test.properties" } ); runUnarchiver( "", new FileSelector[] { fileSelector }, new boolean[] { false, false, true } ); fileSelector.setIncludes( new String[] { "**/test.properties" } ); fileSelector.setExcludes( null ); runUnarchiver( "", new FileSelector[] { fileSelector }, new boolean[] { true, true, false } ); fileSelector.setExcludes( new String[] { "resources/artifactId/directory/test.properties" } ); runUnarchiver( "", new FileSelector[] { fileSelector }, new boolean[] { true, false, false } ); } public void testExtractingZipWithEntryOutsideDestDirThrowsException() throws Exception { Exception ex = null; String s = "target/zip-unarchiver-slip-tests"; File testZip = new File( getBasedir(), "src/test/zips/zip-slip.zip" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); try { ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.extract( "", outputDirectory ); } catch ( Exception e ) { ex = e; } assertNotNull( ex ); assertTrue( ex.getMessage().startsWith( "Entry is outside of the target directory" ) ); } private ZipArchiver getZipArchiver() { try { return (ZipArchiver) lookup( Archiver.ROLE, "zip" ); } catch ( Exception e ) { throw new RuntimeException( e ); } } private ZipArchiver getZipArchiver( File destFile ) { final ZipArchiver zipArchiver = getZipArchiver(); zipArchiver.setDestFile( destFile ); return zipArchiver; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_67_1
crossvul-java_data_good_499_0
package cc.mrbird.common.controller; import cc.mrbird.common.exception.FileDownloadException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; @Controller public class CommonController { private Logger log = LoggerFactory.getLogger(this.getClass()); @RequestMapping("common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) throws IOException, FileDownloadException { if (StringUtils.isNotBlank(fileName) && !fileName.endsWith(".xlsx") && !fileName.endsWith(".csv")) throw new FileDownloadException("不支持该类型文件下载"); String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('_') + 1); String filePath = "file/" + fileName; File file = new File(filePath); if (!file.exists()) throw new FileDownloadException("文件未找到"); response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(realFileName, "utf-8")); response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } } catch (Exception e) { log.error("文件下载失败", e); } finally { if (delete) Files.delete(Paths.get(filePath)); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_499_0
crossvul-java_data_bad_67_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_67_0
crossvul-java_data_good_4612_0
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby; import com.google.common.base.Joiner; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.escape.Escaper; import com.google.common.html.HtmlEscapers; import com.google.common.net.UrlEscapers; import com.google.common.util.concurrent.MoreExecutors; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.google.inject.internal.ProviderMethodsModule; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.util.Types; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import static com.typesafe.config.ConfigValueFactory.fromAnyRef; import static java.util.Objects.requireNonNull; import static org.jooby.Route.CONNECT; import static org.jooby.Route.DELETE; import org.jooby.Route.Definition; import static org.jooby.Route.GET; import static org.jooby.Route.HEAD; import org.jooby.Route.Mapper; import static org.jooby.Route.OPTIONS; import static org.jooby.Route.PATCH; import static org.jooby.Route.POST; import static org.jooby.Route.PUT; import static org.jooby.Route.TRACE; import org.jooby.Session.Store; import org.jooby.funzy.Throwing; import org.jooby.funzy.Try; import org.jooby.handlers.AssetHandler; import org.jooby.internal.AppPrinter; import org.jooby.internal.BuiltinParser; import org.jooby.internal.BuiltinRenderer; import org.jooby.internal.CookieSessionManager; import org.jooby.internal.DefaulErrRenderer; import org.jooby.internal.HttpHandlerImpl; import org.jooby.internal.JvmInfo; import org.jooby.internal.LocaleUtils; import org.jooby.internal.ParameterNameProvider; import org.jooby.internal.RequestScope; import org.jooby.internal.RouteMetadata; import org.jooby.internal.ServerExecutorProvider; import org.jooby.internal.ServerLookup; import org.jooby.internal.ServerSessionManager; import org.jooby.internal.SessionManager; import org.jooby.internal.SourceProvider; import org.jooby.internal.TypeConverters; import org.jooby.internal.handlers.HeadHandler; import org.jooby.internal.handlers.OptionsHandler; import org.jooby.internal.handlers.TraceHandler; import org.jooby.internal.mvc.MvcRoutes; import org.jooby.internal.mvc.MvcWebSocket; import org.jooby.internal.parser.BeanParser; import org.jooby.internal.parser.DateParser; import org.jooby.internal.parser.LocalDateParser; import org.jooby.internal.parser.LocaleParser; import org.jooby.internal.parser.ParserExecutor; import org.jooby.internal.parser.StaticMethodParser; import org.jooby.internal.parser.StringConstructorParser; import org.jooby.internal.parser.ZonedDateTimeParser; import org.jooby.internal.ssl.SslContextProvider; import org.jooby.mvc.Consumes; import org.jooby.mvc.Produces; import org.jooby.scope.Providers; import org.jooby.scope.RequestScoped; import org.jooby.spi.HttpHandler; import org.jooby.spi.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Singleton; import javax.net.ssl.SSLContext; import java.io.File; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; /** * <h1>jooby</h1> * <h2>getting started</h2> * * <pre> * public class MyApp extends Jooby { * * { * use(new Jackson()); // 1. JSON serializer. * * // 2. Define a route * get("/", req {@literal ->} { * Map{@literal <}String, Object{@literal >} model = ...; * return model; * } * } * * public static void main(String[] args) { * run(MyApp::new, args); // 3. Done! * } * } * </pre> * * <h2>application.conf</h2> * <p> * Jooby delegate configuration management to <a * href="https://github.com/typesafehub/config">TypeSafe Config</a>. * </p> * * <p> * By default Jooby looks for an <code>application.conf</code>. If * you want to specify a different file or location, you can do it with {@link #conf(String)}. * </p> * * <p> * <a href="https://github.com/typesafehub/config">TypeSafe Config</a> uses a hierarchical model to * define and override properties. * </p> * <p> * A {@link Jooby.Module} might provides his own set of properties through the * {@link Jooby.Module#config()} method. By default, this method returns an empty config object. * </p> * For example: * * <pre> * use(new M1()); * use(new M2()); * use(new M3()); * </pre> * * Previous example had the following order (first-listed are higher priority): * <ul> * <li>arguments properties</li> * <li>System properties</li> * <li>application.conf</li> * <li>M3 properties</li> * <li>M2 properties</li> * <li>M1 properties</li> * </ul> * <p> * Command line argmuents or system properties takes precedence over any application specific * property. * </p> * * <h2>env</h2> * <p> * Jooby defines one mode or environment: <strong>dev</strong>. In Jooby, <strong>dev</strong> * is special and some modules could apply special settings while running in <strong>dev</strong>. * Any other env is usually considered a <code>prod</code> like env. But that depends on module * implementor. * </p> * <p> * An <code>environment</code> can be defined in your <code>.conf</code> file using the * <code>application.env</code> property. If missing, Jooby set the <code>env</code> for you to * <strong>dev</strong>. * </p> * <p> * There is more at {@link Env} please read the {@link Env} javadoc. * </p> * * <h2>modules: the jump to full-stack framework</h2> * <p> * {@link Jooby.Module Modules} are quite similar to a Guice modules except that the configure * callback has been complementing with {@link Env} and {@link Config}. * </p> * * <pre> * public class MyModule implements Jooby.Module { * public void configure(Env env, Config config, Binder binder) { * } * } * </pre> * * From the configure callback you can bind your services as you usually do in a Guice app. * <p> * There is more at {@link Jooby.Module} so please read the {@link Jooby.Module} javadoc. * </p> * * <h2>path patterns</h2> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.html} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the * {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h3>variables</h3> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * <h2>routes</h2> * <p> * Routes perform actions in response to a server HTTP request. * </p> * <p> * Routes are executed in the order they are defined, for example: * </p> * * <pre> * get("/", (req, rsp) {@literal ->} { * log.info("first"); // start here and go to second * }); * * get("/", (req, rsp) {@literal ->} { * log.info("second"); // execute after first and go to final * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Previous example can be rewritten using {@link Route.Filter}: * * <pre> * get("/", (req, rsp, chain) {@literal ->} { * log.info("first"); // start here and go to second * chain.next(req, rsp); * }); * * get("/", (req, rsp, chain) {@literal ->} { * log.info("second"); // execute after first and go to final * chain.next(req, rsp); * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Due to the use of lambdas a route is a singleton and you should NOT use global variables. For * example this is a bad practice: * * <pre> * List{@literal <}String{@literal >} names = new ArrayList{@literal <}{@literal >}(); // names produces side effects * get("/", (req, rsp) {@literal ->} { * names.add(req.param("name").value(); * // response will be different between calls. * rsp.send(names); * }); * </pre> * * <h3>mvc routes</h3> * <p> * A Mvc route use annotations to define routes: * </p> * * <pre> * use(MyRoute.class); * ... * * // MyRoute.java * {@literal @}Path("/") * public class MyRoute { * * {@literal @}GET * public String hello() { * return "Hello Jooby"; * } * } * </pre> * <p> * Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or * simplifications. * </p> * * <p> * To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path}, * {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes} javadoc. * </p> * * <h2>static files</h2> * <p> * Static files, like: *.js, *.css, ..., etc... can be served with: * </p> * * <pre> * assets("assets/**"); * </pre> * <p> * Classpath resources under the <code>/assets</code> folder will be accessible from client/browser. * </p> * * <h2>lifecyle</h2> * <p> * We do provide {@link #onStart(Throwing.Consumer)} and {@link #onStop(Throwing.Consumer)} callbacks. * These callbacks are executed are application startup or shutdown time: * </p> * * <pre>{@code * { * onStart(() -> { * log.info("Welcome!"); * }); * * onStop(() -> { * log.info("Bye!"); * }); * } * }</pre> * * <p> * From life cycle callbacks you can access to application services: * </p> * * <pre>{@code * { * onStart(registry -> { * MyDatabase db = registry.require(MyDatabase.class); * // do something with databse: * }); * } * }</pre> * * @author edgar * @see Jooby.Module * @since 0.1.0 */ public class Jooby implements Router, LifeCycle, Registry { /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(() -> { * // run something on prod * }); * } * }</pre> */ public interface EnvPredicate { /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(() -> { * // run something on prod * }); * } * }</pre> * * @param callback Env callback. */ default void orElse(final Runnable callback) { orElse(conf -> callback.run()); } /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(conf -> { * // run something on prod * }); * } * }</pre> * * @param callback Env callback. */ void orElse(Consumer<Config> callback); } /** * A module can publish or produces: {@link Route.Definition routes}, {@link Parser}, * {@link Renderer}, and any other application specific service or contract of your choice. * <p> * It is similar to {@link com.google.inject.Module} except for the callback method receives a * {@link Env}, {@link Config} and {@link Binder}. * </p> * * <p> * A module can provide his own set of properties through the {@link #config()} method. By * default, this method returns an empty config object. * </p> * For example: * * <pre> * use(new M1()); * use(new M2()); * use(new M3()); * </pre> * * Previous example had the following order (first-listed are higher priority): * <ul> * <li>System properties</li> * <li>application.conf</li> * <li>M3 properties</li> * <li>M2 properties</li> * <li>M1 properties</li> * </ul> * * <p> * A module can provide start/stop methods in order to start or close resources. * </p> * * @author edgar * @see Jooby#use(Jooby.Module) * @since 0.1.0 */ public interface Module { /** * @return Produces a module config object (when need it). By default a module doesn't produce * any configuration object. */ @Nonnull default Config config() { return ConfigFactory.empty(); } /** * Configure and produces bindings for the underlying application. A module can optimize or * customize a service by checking current the {@link Env application env} and/or the current * application properties available from {@link Config}. * * @param env The current application's env. Not null. * @param conf The current config object. Not null. * @param binder A guice binder. Not null. * @throws Throwable If something goes wrong. */ void configure(Env env, Config conf, Binder binder) throws Throwable; } static class MvcClass implements Route.Props<MvcClass> { Class<?> routeClass; String path; ImmutableMap.Builder<String, Object> attrs = ImmutableMap.builder(); private List<MediaType> consumes; private String name; private List<MediaType> produces; private List<String> excludes; private Mapper<?> mapper; private String prefix; private String renderer; public MvcClass(final Class<?> routeClass, final String path, final String prefix) { this.routeClass = routeClass; this.path = path; this.prefix = prefix; } @Override public MvcClass attr(final String name, final Object value) { attrs.put(name, value); return this; } @Override public MvcClass name(final String name) { this.name = name; return this; } @Override public MvcClass consumes(final List<MediaType> consumes) { this.consumes = consumes; return this; } @Override public MvcClass produces(final List<MediaType> produces) { this.produces = produces; return this; } @Override public MvcClass excludes(final List<String> excludes) { this.excludes = excludes; return this; } @Override public MvcClass map(final Mapper<?> mapper) { this.mapper = mapper; return this; } @Override public String renderer() { return renderer; } @Override public MvcClass renderer(final String name) { this.renderer = name; return this; } public Route.Definition apply(final Route.Definition route) { attrs.build().forEach(route::attr); if (name != null) { route.name(name); } if (prefix != null) { route.name(prefix + "/" + route.name()); } if (consumes != null) { route.consumes(consumes); } if (produces != null) { route.produces(produces); } if (excludes != null) { route.excludes(excludes); } if (mapper != null) { route.map(mapper); } if (renderer != null) { route.renderer(renderer); } return route; } } private static class EnvDep { Predicate<String> predicate; Consumer<Config> callback; public EnvDep(final Predicate<String> predicate, final Consumer<Config> callback) { this.predicate = predicate; this.callback = callback; } } static { // set pid as system property String pid = System.getProperty("pid", JvmInfo.pid() + ""); System.setProperty("pid", pid); } /** * Keep track of routes. */ private transient Set<Object> bag = new LinkedHashSet<>(); /** * The override config. Optional. */ private transient Config srcconf; private final transient AtomicBoolean started = new AtomicBoolean(false); /** Keep the global injector instance. */ private transient Injector injector; /** Session store. */ private transient Session.Definition session = new Session.Definition(Session.Mem.class); /** Env builder. */ private transient Env.Builder env = Env.DEFAULT; /** Route's prefix. */ private transient String prefix; /** startup callback . */ private transient List<Throwing.Consumer<Registry>> onStart = new ArrayList<>(); private transient List<Throwing.Consumer<Registry>> onStarted = new ArrayList<>(); /** stop callback . */ private transient List<Throwing.Consumer<Registry>> onStop = new ArrayList<>(); /** Mappers . */ @SuppressWarnings("rawtypes") private transient Mapper mapper; /** Don't add same mapper twice . */ private transient Set<String> mappers = new HashSet<>(); /** Bean parser . */ private transient Optional<Parser> beanParser = Optional.empty(); private transient ServerLookup server = new ServerLookup(); private transient String dateFormat; private transient Charset charset; private transient String[] languages; private transient ZoneId zoneId; private transient Integer port; private transient Integer securePort; private transient String numberFormat; private transient boolean http2; private transient List<Consumer<Binder>> executors = new ArrayList<>(); private transient boolean defaultExecSet; private boolean throwBootstrapException; /** * creates the injector */ private transient BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory = Guice::createInjector; private transient List<Jooby> apprefs; private transient LinkedList<String> path = new LinkedList<>(); private transient String confname; private transient boolean caseSensitiveRouting = true; private transient String classname; /** * Creates a new {@link Jooby} application. */ public Jooby() { this(null); } /** * Creates a new application and prefix all the names of the routes with the given prefix. Useful, * for dynamic/advanced routing. See {@link Route.Chain#next(String, Request, Response)}. * * @param prefix Route name prefix. */ public Jooby(final String prefix) { this.prefix = prefix; use(server); this.classname = classname(getClass().getName()); } @Override public Route.Collection path(String path, Runnable action) { this.path.addLast(Route.normalize(path)); Route.Collection collection = with(action); this.path.removeLast(); return collection; } @Override public Jooby use(final Jooby app) { return use(prefixPath(null), app); } private Optional<String> prefixPath(@Nullable String tail) { return path.size() == 0 ? tail == null ? Optional.empty() : Optional.of(Route.normalize(tail)) : Optional.of(path.stream() .collect(Collectors.joining("", "", tail == null ? "" : Route.normalize(tail)))); } @Override public Jooby use(final String path, final Jooby app) { return use(prefixPath(path), app); } /** * Use the provided HTTP server. * * @param server Server. * @return This jooby instance. */ public Jooby server(final Class<? extends Server> server) { requireNonNull(server, "Server required."); // remove server lookup List<Object> tmp = bag.stream() .skip(1) .collect(Collectors.toList()); tmp.add(0, (Module) (env, conf, binder) -> binder.bind(Server.class).to(server).asEagerSingleton()); bag.clear(); bag.addAll(tmp); return this; } private Jooby use(final Optional<String> path, final Jooby app) { requireNonNull(app, "App is required."); Function<Route.Definition, Route.Definition> rewrite = r -> { return path.map(p -> { Route.Definition result = new Route.Definition(r.method(), p + r.pattern(), r.filter()); result.consumes(r.consumes()); result.produces(r.produces()); result.excludes(r.excludes()); return result; }).orElse(r); }; app.bag.forEach(it -> { if (it instanceof Route.Definition) { this.bag.add(rewrite.apply((Definition) it)); } else if (it instanceof MvcClass) { Object routes = path.<Object>map(p -> new MvcClass(((MvcClass) it).routeClass, p, prefix)) .orElse(it); this.bag.add(routes); } else { // everything else this.bag.add(it); } }); // start/stop callback app.onStart.forEach(this.onStart::add); app.onStarted.forEach(this.onStarted::add); app.onStop.forEach(this.onStop::add); // mapper if (app.mapper != null) { this.map(app.mapper); } if (apprefs == null) { apprefs = new ArrayList<>(); } apprefs.add(app); return this; } /** * Set a custom {@link Env.Builder} to use. * * @param env A custom env builder. * @return This jooby instance. */ public Jooby env(final Env.Builder env) { this.env = requireNonNull(env, "Env builder is required."); return this; } @Override public Jooby onStart(final Throwing.Runnable callback) { LifeCycle.super.onStart(callback); return this; } @Override public Jooby onStart(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStart.add(callback); return this; } @Override public Jooby onStarted(final Throwing.Runnable callback) { LifeCycle.super.onStarted(callback); return this; } @Override public Jooby onStarted(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStarted.add(callback); return this; } @Override public Jooby onStop(final Throwing.Runnable callback) { LifeCycle.super.onStop(callback); return this; } @Override public Jooby onStop(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStop.add(callback); return this; } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }).orElse(() {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param env Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final String env, final Runnable callback) { requireNonNull(env, "Env is required."); return on(envpredicate(env), callback); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on("dev", conf {@literal ->} { * use(new DevModule()); * }).orElse(conf {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param env Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final String env, final Consumer<Config> callback) { requireNonNull(env, "Env is required."); return on(envpredicate(env), callback); } /** * Run the given callback if and only if, application runs in the given envirobment. * * <pre> * { * on("dev", "test", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on(env {@literal ->} env.equals("dev"), () {@literal ->} { * use(new DevModule()); * }).orElse(() {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param predicate Predicate to check the environment. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final Predicate<String> predicate, final Runnable callback) { requireNonNull(predicate, "Predicate is required."); requireNonNull(callback, "Callback is required."); return on(predicate, conf -> callback.run()); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on(env {@literal ->} env.equals("dev"), conf {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * @param predicate Predicate to check the environment. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final Predicate<String> predicate, final Consumer<Config> callback) { requireNonNull(predicate, "Predicate is required."); requireNonNull(callback, "Callback is required."); this.bag.add(new EnvDep(predicate, callback)); return otherwise -> this.bag.add(new EnvDep(predicate.negate(), otherwise)); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", "test", "mock", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * @param env1 Environment where we want to run the callback. * @param env2 Environment where we want to run the callback. * @param env3 Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public Jooby on(final String env1, final String env2, final String env3, final Runnable callback) { on(envpredicate(env1).or(envpredicate(env2)).or(envpredicate(env3)), callback); return this; } @Override public <T> T require(final Key<T> type) { checkState(injector != null, "Registry is not ready. Require calls are available at application startup time, see http://jooby.org/doc/#application-life-cycle"); try { return injector.getInstance(type); } catch (ProvisionException x) { Throwable cause = x.getCause(); if (cause instanceof Err) { throw (Err) cause; } throw x; } } @Override public Route.OneArgHandler promise(final Deferred.Initializer initializer) { return req -> { return new Deferred(initializer); }; } @Override public Route.OneArgHandler promise(final String executor, final Deferred.Initializer initializer) { return req -> new Deferred(executor, initializer); } @Override public Route.OneArgHandler promise(final Deferred.Initializer0 initializer) { return req -> { return new Deferred(initializer); }; } @Override public Route.OneArgHandler promise(final String executor, final Deferred.Initializer0 initializer) { return req -> new Deferred(executor, initializer); } /** * Setup a session store to use. Useful if you want/need to persist sessions between shutdowns, * apply timeout policies, etc... * * Jooby comes with a dozen of {@link Session.Store}, checkout the * <a href="http://jooby.org/doc/session">session modules</a>. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @param store A session store. * @return A session store definition. */ public Session.Definition session(final Class<? extends Session.Store> store) { this.session = new Session.Definition(requireNonNull(store, "A session store is required.")); return this.session; } /** * Setup a session store that saves data in a the session cookie. It makes the application * stateless, which help to scale easily. Keep in mind that a cookie has a limited size (up to * 4kb) so you must pay attention to what you put in the session object (don't use as cache). * * Cookie session signed data using the <code>application.secret</code> property, so you must * provide an <code>application.secret</code> value. On dev environment you can set it in your * <code>.conf</code> file. In prod is probably better to provide as command line argument and/or * environment variable. Just make sure to keep it private. * * Please note {@link Session#id()}, {@link Session#accessedAt()}, etc.. make no sense for cookie * sessions, just the {@link Session#attributes()}. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @return A session definition/configuration object. */ public Session.Definition cookieSession() { this.session = new Session.Definition(); return this.session; } /** * Setup a session store to use. Useful if you want/need to persist sessions between shutdowns, * apply timeout policies, etc... * * Jooby comes with a dozen of {@link Session.Store}, checkout the * <a href="http://jooby.org/doc/session">session modules</a>. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @param store A session store. * @return A session store definition. */ public Session.Definition session(final Session.Store store) { this.session = new Session.Definition(requireNonNull(store, "A session store is required.")); return this.session; } /** * Register a new param/body converter. See {@link Parser} for more details. * * @param parser A parser. * @return This jooby instance. */ public Jooby parser(final Parser parser) { if (parser instanceof BeanParser) { beanParser = Optional.of(parser); } else { bag.add(requireNonNull(parser, "A parser is required.")); } return this; } /** * Append a response {@link Renderer} for write HTTP messages. * * @param renderer A renderer renderer. * @return This jooby instance. */ public Jooby renderer(final Renderer renderer) { this.bag.add(requireNonNull(renderer, "A renderer is required.")); return this; } @Override public Route.Definition before(final String method, final String pattern, final Route.Before handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition after(final String method, final String pattern, final Route.After handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition complete(final String method, final String pattern, final Route.Complete handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition use(final String path, final Route.Filter filter) { return appendDefinition("*", path, filter); } @Override public Route.Definition use(final String verb, final String path, final Route.Filter filter) { return appendDefinition(verb, path, filter); } @Override public Route.Definition use(final String verb, final String path, final Route.Handler handler) { return appendDefinition(verb, path, handler); } @Override public Route.Definition use(final String path, final Route.Handler handler) { return appendDefinition("*", path, handler); } @Override public Route.Definition use(final String path, final Route.OneArgHandler handler) { return appendDefinition("*", path, handler); } @Override public Route.Definition get(final String path, final Route.Handler handler) { if (handler instanceof AssetHandler) { return assets(path, (AssetHandler) handler); } else { return appendDefinition(GET, path, handler); } } @Override public Route.Collection get(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.OneArgHandler handler) { return appendDefinition(GET, path, handler); } @Override public Route.Collection get(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(GET, path, handler); } @Override public Route.Collection get(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.Filter filter) { return appendDefinition(GET, path, filter); } @Override public Route.Collection get(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection(new Route.Definition[]{get(path1, filter), get(path2, filter)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{get(path1, filter), get(path2, filter), get(path3, filter)}); } @Override public Route.Definition post(final String path, final Route.Handler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.OneArgHandler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.Filter filter) { return appendDefinition(POST, path, filter); } @Override public Route.Collection post(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{post(path1, filter), post(path2, filter)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{post(path1, filter), post(path2, filter), post(path3, filter)}); } @Override public Route.Definition head(final String path, final Route.Handler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.OneArgHandler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.Filter filter) { return appendDefinition(HEAD, path, filter); } @Override public Route.Definition head() { return appendDefinition(HEAD, "*", filter(HeadHandler.class)).name("*.head"); } @Override public Route.Definition options(final String path, final Route.Handler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.OneArgHandler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.Filter filter) { return appendDefinition(OPTIONS, path, filter); } @Override public Route.Definition options() { return appendDefinition(OPTIONS, "*", handler(OptionsHandler.class)).name("*.options"); } @Override public Route.Definition put(final String path, final Route.Handler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.OneArgHandler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.Filter filter) { return appendDefinition(PUT, path, filter); } @Override public Route.Collection put(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{put(path1, filter), put(path2, filter)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{put(path1, filter), put(path2, filter), put(path3, filter)}); } @Override public Route.Definition patch(final String path, final Route.Handler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.OneArgHandler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.Filter filter) { return appendDefinition(PATCH, path, filter); } @Override public Route.Collection patch(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{patch(path1, filter), patch(path2, filter)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{patch(path1, filter), patch(path2, filter), patch(path3, filter)}); } @Override public Route.Definition delete(final String path, final Route.Handler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.OneArgHandler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.Filter filter) { return appendDefinition(DELETE, path, filter); } @Override public Route.Collection delete(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{delete(path1, filter), delete(path2, filter)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{delete(path1, filter), delete(path2, filter), delete(path3, filter)}); } @Override public Route.Definition trace(final String path, final Route.Handler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.OneArgHandler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.Filter filter) { return appendDefinition(TRACE, path, filter); } @Override public Route.Definition trace() { return appendDefinition(TRACE, "*", handler(TraceHandler.class)).name("*.trace"); } @Override public Route.Definition connect(final String path, final Route.Handler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.OneArgHandler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.Filter filter) { return appendDefinition(CONNECT, path, filter); } /** * Creates a new {@link Route.Handler} that delegate the execution to the given handler. This is * useful when the target handler requires some dependencies. * * <pre> * public class MyHandler implements Route.Handler { * &#64;Inject * public MyHandler(Dependency d) { * } * * public void handle(Request req, Response rsp) throws Exception { * // do something * } * } * ... * // external route * get("/", handler(MyHandler.class)); * * // inline version route * get("/", (req, rsp) {@literal ->} { * Dependency d = req.getInstance(Dependency.class); * // do something * }); * </pre> * * You can access to a dependency from a in-line route too, so the use of external route it is * more or less a matter of taste. * * @param handler The external handler class. * @return A new inline route handler. */ private Route.Handler handler(final Class<? extends Route.Handler> handler) { requireNonNull(handler, "Route handler is required."); return (req, rsp) -> req.require(handler).handle(req, rsp); } /** * Creates a new {@link Route.Filter} that delegate the execution to the given filter. This is * useful when the target handler requires some dependencies. * * <pre> * public class MyFilter implements Filter { * &#64;Inject * public MyFilter(Dependency d) { * } * * public void handle(Request req, Response rsp, Route.Chain chain) throws Exception { * // do something * } * } * ... * // external filter * get("/", filter(MyFilter.class)); * * // inline version route * get("/", (req, rsp, chain) {@literal ->} { * Dependency d = req.getInstance(Dependency.class); * // do something * }); * </pre> * * You can access to a dependency from a in-line route too, so the use of external filter it is * more or less a matter of taste. * * @param filter The external filter class. * @return A new inline route. */ private Route.Filter filter(final Class<? extends Route.Filter> filter) { requireNonNull(filter, "Filter is required."); return (req, rsp, chain) -> req.require(filter).handle(req, rsp, chain); } @Override public Route.AssetDefinition assets(final String path, final Path basedir) { return assets(path, new AssetHandler(basedir)); } @Override public Route.AssetDefinition assets(final String path, final String location) { return assets(path, new AssetHandler(location)); } @Override public Route.AssetDefinition assets(final String path, final AssetHandler handler) { Route.AssetDefinition route = appendDefinition(GET, path, handler, Route.AssetDefinition::new); return configureAssetHandler(route); } @Override public Route.Collection use(final Class<?> routeClass) { return use("", routeClass); } @Override public Route.Collection use(final String path, final Class<?> routeClass) { requireNonNull(routeClass, "Route class is required."); requireNonNull(path, "Path is required"); MvcClass mvc = new MvcClass(routeClass, path, prefix); bag.add(mvc); return new Route.Collection(mvc); } /** * Keep track of routes in the order user define them. * * @param method Route method. * @param pattern Route pattern. * @param filter Route filter. * @return The same route definition. */ private Route.Definition appendDefinition(String method, String pattern, Route.Filter filter) { return appendDefinition(method, pattern, filter, Route.Definition::new); } /** * Keep track of routes in the order user define them. * * @param method Route method. * @param pattern Route pattern. * @param filter Route filter. * @param creator Route creator. * @return The same route definition. */ private <T extends Route.Definition> T appendDefinition(String method, String pattern, Route.Filter filter, Throwing.Function4<String, String, Route.Filter, Boolean, T> creator) { String pathPattern = prefixPath(pattern).orElse(pattern); T route = creator.apply(method, pathPattern, filter, caseSensitiveRouting); if (prefix != null) { route.prefix = prefix; // reset name will update the name if prefix != null route.name(route.name()); } bag.add(route); return route; } /** * Import an application {@link Module}. * * @param module The module to import. * @return This jooby instance. * @see Jooby.Module */ public Jooby use(final Jooby.Module module) { requireNonNull(module, "A module is required."); bag.add(module); return this; } /** * Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code> * file. * * @param path Classpath location. * @return This jooby instance. */ public Jooby conf(final String path) { this.confname = path; use(ConfigFactory.parseResources(path)); return this; } /** * Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code> * file. * * @param path File system location. * @return This jooby instance. */ public Jooby conf(final File path) { this.confname = path.getName(); use(ConfigFactory.parseFile(path)); return this; } /** * Set the application configuration object. You must call this method when the default file * name: <code>application.conf</code> doesn't work for you or when you need/want to register two * or more files. * * @param config The application configuration object. * @return This jooby instance. * @see Config */ public Jooby use(final Config config) { this.srcconf = requireNonNull(config, "Config required."); return this; } @Override public Jooby err(final Err.Handler err) { this.bag.add(requireNonNull(err, "An err handler is required.")); return this; } @Override public WebSocket.Definition ws(final String path, final WebSocket.OnOpen handler) { WebSocket.Definition ws = new WebSocket.Definition(path, handler); checkArgument(bag.add(ws), "Duplicated path: '%s'", path); return ws; } @Override public <T> WebSocket.Definition ws(final String path, final Class<? extends WebSocket.OnMessage<T>> handler) { String fpath = Optional.ofNullable(handler.getAnnotation(org.jooby.mvc.Path.class)) .map(it -> path + "/" + it.value()[0]) .orElse(path); WebSocket.Definition ws = ws(fpath, MvcWebSocket.newWebSocket(handler)); Optional.ofNullable(handler.getAnnotation(Consumes.class)) .ifPresent(consumes -> Arrays.asList(consumes.value()).forEach(ws::consumes)); Optional.ofNullable(handler.getAnnotation(Produces.class)) .ifPresent(produces -> Arrays.asList(produces.value()).forEach(ws::produces)); return ws; } @Override public Route.Definition sse(final String path, final Sse.Handler handler) { return appendDefinition(GET, path, handler).consumes(MediaType.sse); } @Override public Route.Definition sse(final String path, final Sse.Handler1 handler) { return appendDefinition(GET, path, handler).consumes(MediaType.sse); } @SuppressWarnings("rawtypes") @Override public Route.Collection with(final Runnable callback) { // hacky way of doing what we want... but we do simplify developer life int size = this.bag.size(); callback.run(); // collect latest routes and apply route props List<Route.Props> local = this.bag.stream() .skip(size) .filter(Route.Props.class::isInstance) .map(Route.Props.class::cast) .collect(Collectors.toList()); return new Route.Collection(local.toArray(new Route.Props[local.size()])); } /** * Prepare and startup a {@link Jooby} application. * * @param app Application supplier. * @param args Application arguments. */ public static void run(final Supplier<? extends Jooby> app, final String... args) { Config conf = ConfigFactory.systemProperties() .withFallback(args(args)); System.setProperty("logback.configurationFile", logback(conf)); app.get().start(args); } /** * Prepare and startup a {@link Jooby} application. * * @param app Application supplier. * @param args Application arguments. */ public static void run(final Class<? extends Jooby> app, final String... args) { run(() -> Try.apply(() -> app.newInstance()).get(), args); } /** * Export configuration from an application. Useful for tooling, testing, debugging, etc... * * @param app Application to extract/collect configuration. * @return Application conf or <code>empty</code> conf on error. */ public static Config exportConf(final Jooby app) { AtomicReference<Config> conf = new AtomicReference<>(ConfigFactory.empty()); app.on("*", c -> { conf.set(c); }); exportRoutes(app); return conf.get(); } /** * Export routes from an application. Useful for route analysis, testing, debugging, etc... * * @param app Application to extract/collect routes. * @return Application routes. */ public static List<Definition> exportRoutes(final Jooby app) { @SuppressWarnings("serial") class Success extends RuntimeException { List<Definition> routes; Success(final List<Route.Definition> routes) { this.routes = routes; } } List<Definition> routes = Collections.emptyList(); try { app.start(new String[0], r -> { throw new Success(r); }); } catch (Success success) { routes = success.routes; } catch (Throwable x) { logger(app).debug("Failed bootstrap: {}", app, x); } return routes; } /** * Start an application. Fire the {@link #onStart(Throwing.Runnable)} event and the * {@link #onStarted(Throwing.Runnable)} events. */ public void start() { start(new String[0]); } /** * Start an application. Fire the {@link #onStart(Throwing.Runnable)} event and the * {@link #onStarted(Throwing.Runnable)} events. * * @param args Application arguments. */ public void start(final String... args) { try { start(args, null); } catch (Throwable x) { stop(); String msg = "An error occurred while starting the application:"; if (throwBootstrapException) { throw new Err(Status.SERVICE_UNAVAILABLE, msg, x); } else { logger(this).error(msg, x); } } } @SuppressWarnings("unchecked") private void start(final String[] args, final Consumer<List<Route.Definition>> routes) throws Throwable { long start = System.currentTimeMillis(); started.set(true); this.injector = bootstrap(args(args), routes); // shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); Config conf = injector.getInstance(Config.class); Logger log = logger(this); // inject class injector.injectMembers(this); // onStart callbacks via .conf if (conf.hasPath("jooby.internal.onStart")) { ClassLoader loader = getClass().getClassLoader(); Object internalOnStart = loader.loadClass(conf.getString("jooby.internal.onStart")) .newInstance(); onStart.add((Throwing.Consumer<Registry>) internalOnStart); } // start services for (Throwing.Consumer<Registry> onStart : this.onStart) { onStart.accept(this); } // route mapper Set<Route.Definition> routeDefs = injector.getInstance(Route.KEY); Set<WebSocket.Definition> sockets = injector.getInstance(WebSocket.KEY); if (mapper != null) { routeDefs.forEach(it -> it.map(mapper)); } AppPrinter printer = new AppPrinter(routeDefs, sockets, conf); printer.printConf(log, conf); // Start server Server server = injector.getInstance(Server.class); String serverName = server.getClass().getSimpleName().replace("Server", "").toLowerCase(); server.start(); long end = System.currentTimeMillis(); log.info("[{}@{}]: Server started in {}ms\n\n{}\n", conf.getString("application.env"), serverName, end - start, printer); // started services for (Throwing.Consumer<Registry> onStarted : this.onStarted) { onStarted.accept(this); } boolean join = conf.hasPath("server.join") ? conf.getBoolean("server.join") : true; if (join) { server.join(); } } @Override @SuppressWarnings("unchecked") public Jooby map(final Mapper<?> mapper) { requireNonNull(mapper, "Mapper is required."); if (mappers.add(mapper.name())) { this.mapper = Optional.ofNullable(this.mapper) .map(next -> Route.Mapper.chain(mapper, next)) .orElse((Mapper<Object>) mapper); } return this; } /** * Use the injection provider to create the Guice injector * * @param injectorFactory the injection provider * @return this instance. */ public Jooby injector( final BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory) { this.injectorFactory = injectorFactory; return this; } /** * Bind the provided abstract type to the given implementation: * * <pre> * { * bind(MyInterface.class, MyImplementation.class); * } * </pre> * * @param type Service interface. * @param implementation Service implementation. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Class<? extends T> implementation) { use((env, conf, binder) -> { binder.bind(type).to(implementation); }); return this; } /** * Bind the provided abstract type to the given implementation: * * <pre> * { * bind(MyInterface.class, MyImplementation::new); * } * </pre> * * @param type Service interface. * @param implementation Service implementation. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Supplier<T> implementation) { use((env, conf, binder) -> { binder.bind(type).toInstance(implementation.get()); }); return this; } /** * Bind the provided type: * * <pre> * { * bind(MyInterface.class); * } * </pre> * * @param type Service interface. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type) { use((env, conf, binder) -> { binder.bind(type); }); return this; } /** * Bind the provided type: * * <pre> * { * bind(new MyService()); * } * </pre> * * @param service Service. * @return This instance. */ @SuppressWarnings({"rawtypes", "unchecked"}) public Jooby bind(final Object service) { use((env, conf, binder) -> { Class type = service.getClass(); binder.bind(type).toInstance(service); }); return this; } /** * Bind the provided type and object that requires some type of configuration: * * <pre>{@code * { * bind(MyService.class, conf -> new MyService(conf.getString("service.url"))); * } * }</pre> * * @param type Service type. * @param provider Service provider. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Function<Config, ? extends T> provider) { use((env, conf, binder) -> { T service = provider.apply(conf); binder.bind(type).toInstance(service); }); return this; } /** * Bind the provided type and object that requires some type of configuration: * * <pre>{@code * { * bind(conf -> new MyService(conf.getString("service.url"))); * } * }</pre> * * @param provider Service provider. * @param <T> Service type. * @return This instance. */ @SuppressWarnings({"unchecked", "rawtypes"}) public <T> Jooby bind(final Function<Config, T> provider) { use((env, conf, binder) -> { Object service = provider.apply(conf); Class type = service.getClass(); binder.bind(type).toInstance(service); }); return this; } /** * Set application date format. * * @param dateFormat A date format. * @return This instance. */ public Jooby dateFormat(final String dateFormat) { this.dateFormat = requireNonNull(dateFormat, "DateFormat required."); return this; } /** * Set application number format. * * @param numberFormat A number format. * @return This instance. */ public Jooby numberFormat(final String numberFormat) { this.numberFormat = requireNonNull(numberFormat, "NumberFormat required."); return this; } /** * Set application/default charset. * * @param charset A charset. * @return This instance. */ public Jooby charset(final Charset charset) { this.charset = requireNonNull(charset, "Charset required."); return this; } /** * Set application locale (first listed are higher priority). * * @param languages List of locale using the language tag format. * @return This instance. */ public Jooby lang(final String... languages) { this.languages = languages; return this; } /** * Set application time zone. * * @param zoneId ZoneId. * @return This instance. */ public Jooby timezone(final ZoneId zoneId) { this.zoneId = requireNonNull(zoneId, "ZoneId required."); return this; } /** * Set the HTTP port. * * <p> * Keep in mind this work as a default port and can be reset via <code>application.port</code> * property. * </p> * * @param port HTTP port. * @return This instance. */ public Jooby port(final int port) { this.port = port; return this; } /** * <p> * Set the HTTPS port to use. * </p> * * <p> * Keep in mind this work as a default port and can be reset via <code>application.port</code> * property. * </p> * * <h2>HTTPS</h2> * <p> * Jooby comes with a self-signed certificate, useful for development and test. But of course, you * should NEVER use it in the real world. * </p> * * <p> * In order to setup HTTPS with a secure certificate, you need to set these properties: * </p> * * <ul> * <li> * <code>ssl.keystore.cert</code>: An X.509 certificate chain file in PEM format. It can be an * absolute path or a classpath resource. * </li> * <li> * <code>ssl.keystore.key</code>: A PKCS#8 private key file in PEM format. It can be an absolute * path or a classpath resource. * </li> * </ul> * * <p> * Optionally, you can set these too: * </p> * * <ul> * <li> * <code>ssl.keystore.password</code>: Password of the keystore.key (if any). Default is: * null/empty. * </li> * <li> * <code>ssl.trust.cert</code>: Trusted certificates for verifying the remote endpoint’s * certificate. The file should contain an X.509 certificate chain in PEM format. Default uses the * system default. * </li> * <li> * <code>ssl.session.cacheSize</code>: Set the size of the cache used for storing SSL session * objects. 0 to use the default value. * </li> * <li> * <code>ssl.session.timeout</code>: Timeout for the cached SSL session objects, in seconds. 0 to * use the default value. * </li> * </ul> * * <p> * As you can see setup is very simple. All you need is your <code>.crt</code> and * <code>.key</code> files. * </p> * * @param port HTTPS port. * @return This instance. */ public Jooby securePort(final int port) { this.securePort = port; return this; } /** * <p> * Enable <code>HTTP/2</code> protocol. Some servers require special configuration, others just * works. It is a good idea to check the server documentation about * <a href="http://jooby.org/doc/servers">HTTP/2</a>. * </p> * * <p> * In order to use HTTP/2 from a browser you must configure HTTPS, see {@link #securePort(int)} * documentation. * </p> * * <p> * If HTTP/2 clear text is supported then you may skip the HTTPS setup, but of course you won't be * able to use HTTP/2 with browsers. * </p> * * @return This instance. */ public Jooby http2() { this.http2 = true; return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final ExecutorService executor) { executor((Executor) executor); onStop(r -> executor.shutdown()); return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final Executor executor) { this.defaultExecSet = true; this.executors.add(binder -> { binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance("deferred"); binder.bind(Key.get(Executor.class, Names.named("deferred"))).toInstance(executor); }); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param name Name of the executor. * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final String name, final ExecutorService executor) { executor(name, (Executor) executor); onStop(r -> executor.shutdown()); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param name Name of the executor. * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final String name, final Executor executor) { this.executors.add(binder -> { binder.bind(Key.get(Executor.class, Names.named(name))).toInstance(executor); }); return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. This works as reference to * an executor, application directly or via module must provide an named executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * @param name Executor to use. * @return This jooby instance. */ public Jooby executor(final String name) { defaultExecSet = true; this.executors.add(binder -> { binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance(name); }); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * @param name Name of the executor. * @param provider Provider for the executor. * @return This jooby instance. */ private Jooby executor(final String name, final Class<? extends Provider<Executor>> provider) { this.executors.add(binder -> { binder.bind(Key.get(Executor.class, Names.named(name))).toProvider(provider) .in(Singleton.class); }); return this; } /** * If the application fails to start all the services are shutdown. Also, the exception is logged * and usually the application is going to exit. * * This options turn off logging and rethrow the exception as {@link Err}. Here is an example: * * <pre> * public class App extends Jooby { * { * throwBootstrapException(); * ... * } * } * * App app = new App(); * * try { * app.start(); * } catch (Err err) { * Throwable cause = err.getCause(); * } * </pre> * * @return This instance. */ public Jooby throwBootstrapException() { this.throwBootstrapException = true; return this; } /** * Configure case for routing algorithm. Default is <code>case sensitive</code>. * * @param enabled True for case sensitive, false otherwise. * @return This instance. */ public Jooby caseSensitiveRouting(boolean enabled) { this.caseSensitiveRouting = enabled; return this; } private static List<Object> normalize(final List<Object> services, final Env env, final RouteMetadata classInfo, final boolean caseSensitiveRouting) { List<Object> result = new ArrayList<>(); List<Object> snapshot = services; /** modules, routes, parsers, renderers and websockets */ snapshot.forEach(candidate -> { if (candidate instanceof Route.Definition) { result.add(candidate); } else if (candidate instanceof MvcClass) { MvcClass mvcRoute = ((MvcClass) candidate); Class<?> mvcClass = mvcRoute.routeClass; String path = ((MvcClass) candidate).path; MvcRoutes.routes(env, classInfo, path, caseSensitiveRouting, mvcClass) .forEach(route -> result.add(mvcRoute.apply(route))); } else { result.add(candidate); } }); return result; } private static List<Object> processEnvDep(final Set<Object> src, final Env env) { List<Object> result = new ArrayList<>(); List<Object> bag = new ArrayList<>(src); bag.forEach(it -> { if (it instanceof EnvDep) { EnvDep envdep = (EnvDep) it; if (envdep.predicate.test(env.name())) { int from = src.size(); envdep.callback.accept(env.config()); int to = src.size(); result.addAll(new ArrayList<>(src).subList(from, to)); } } else { result.add(it); } }); return result; } private Injector bootstrap(final Config args, final Consumer<List<Route.Definition>> rcallback) throws Throwable { Config initconf = Optional.ofNullable(srcconf) .orElseGet(() -> ConfigFactory.parseResources("application.conf")); List<Config> modconf = modconf(this.bag); Config conf = buildConfig(initconf, args, modconf); final List<Locale> locales = LocaleUtils.parse(conf.getString("application.lang")); Env env = this.env.build(conf, this, locales.get(0)); String envname = env.name(); final Charset charset = Charset.forName(conf.getString("application.charset")); String dateFormat = conf.getString("application.dateFormat"); ZoneId zoneId = ZoneId.of(conf.getString("application.tz")); DateTimeFormatter dateTimeFormatter = DateTimeFormatter .ofPattern(dateFormat, locales.get(0)) .withZone(zoneId); DateTimeFormatter zonedDateTimeFormat = DateTimeFormatter .ofPattern(conf.getString("application.zonedDateTimeFormat")); DecimalFormat numberFormat = new DecimalFormat(conf.getString("application.numberFormat")); // Guice Stage Stage stage = "dev".equals(envname) ? Stage.DEVELOPMENT : Stage.PRODUCTION; // expand and normalize bag RouteMetadata rm = new RouteMetadata(env); List<Object> realbag = processEnvDep(this.bag, env); List<Config> realmodconf = modconf(realbag); List<Object> bag = normalize(realbag, env, rm, caseSensitiveRouting); // collect routes and fire route callback if (rcallback != null) { List<Route.Definition> routes = bag.stream() .filter(it -> it instanceof Route.Definition) .map(it -> (Route.Definition) it) .collect(Collectors.<Route.Definition>toList()); rcallback.accept(routes); } // final config ? if we add a mod that depends on env Config finalConfig; Env finalEnv; if (modconf.size() != realmodconf.size()) { finalConfig = buildConfig(initconf, args, realmodconf); finalEnv = this.env.build(finalConfig, this, locales.get(0)); } else { finalConfig = conf; finalEnv = env; } boolean cookieSession = session.store() == null; if (cookieSession && !finalConfig.hasPath("application.secret")) { throw new IllegalStateException("Required property 'application.secret' is missing"); } /** executors: */ if (!defaultExecSet) { // default executor executor(MoreExecutors.directExecutor()); } executor("direct", MoreExecutors.directExecutor()); executor("server", ServerExecutorProvider.class); /** Some basic xss functions. */ xss(finalEnv); /** dependency injection */ @SuppressWarnings("unchecked") com.google.inject.Module joobyModule = binder -> { /** type converters */ new TypeConverters().configure(binder); /** bind config */ bindConfig(binder, finalConfig); /** bind env */ binder.bind(Env.class).toInstance(finalEnv); /** bind charset */ binder.bind(Charset.class).toInstance(charset); /** bind locale */ binder.bind(Locale.class).toInstance(locales.get(0)); TypeLiteral<List<Locale>> localeType = (TypeLiteral<List<Locale>>) TypeLiteral .get(Types.listOf(Locale.class)); binder.bind(localeType).toInstance(locales); /** bind time zone */ binder.bind(ZoneId.class).toInstance(zoneId); binder.bind(TimeZone.class).toInstance(TimeZone.getTimeZone(zoneId)); /** bind date format */ binder.bind(DateTimeFormatter.class).toInstance(dateTimeFormatter); /** bind number format */ binder.bind(NumberFormat.class).toInstance(numberFormat); binder.bind(DecimalFormat.class).toInstance(numberFormat); /** bind ssl provider. */ binder.bind(SSLContext.class).toProvider(SslContextProvider.class); /** routes */ Multibinder<Definition> definitions = Multibinder .newSetBinder(binder, Definition.class); /** web sockets */ Multibinder<WebSocket.Definition> sockets = Multibinder .newSetBinder(binder, WebSocket.Definition.class); /** tmp dir */ File tmpdir = new File(finalConfig.getString("application.tmpdir")); tmpdir.mkdirs(); binder.bind(File.class).annotatedWith(Names.named("application.tmpdir")) .toInstance(tmpdir); binder.bind(ParameterNameProvider.class).toInstance(rm); /** err handler */ Multibinder<Err.Handler> ehandlers = Multibinder .newSetBinder(binder, Err.Handler.class); /** parsers & renderers */ Multibinder<Parser> parsers = Multibinder .newSetBinder(binder, Parser.class); Multibinder<Renderer> renderers = Multibinder .newSetBinder(binder, Renderer.class); /** basic parser */ parsers.addBinding().toInstance(BuiltinParser.Basic); parsers.addBinding().toInstance(BuiltinParser.Collection); parsers.addBinding().toInstance(BuiltinParser.Optional); parsers.addBinding().toInstance(BuiltinParser.Enum); parsers.addBinding().toInstance(BuiltinParser.Bytes); /** basic render */ renderers.addBinding().toInstance(BuiltinRenderer.asset); renderers.addBinding().toInstance(BuiltinRenderer.bytes); renderers.addBinding().toInstance(BuiltinRenderer.byteBuffer); renderers.addBinding().toInstance(BuiltinRenderer.file); renderers.addBinding().toInstance(BuiltinRenderer.charBuffer); renderers.addBinding().toInstance(BuiltinRenderer.stream); renderers.addBinding().toInstance(BuiltinRenderer.reader); renderers.addBinding().toInstance(BuiltinRenderer.fileChannel); /** modules, routes, parsers, renderers and websockets */ Set<Object> routeClasses = new HashSet<>(); for (Object it : bag) { Try.run(() -> bindService( logger(this), this.bag, finalConfig, finalEnv, rm, binder, definitions, sockets, ehandlers, parsers, renderers, routeClasses, caseSensitiveRouting) .accept(it)) .throwException(); } parsers.addBinding().toInstance(new DateParser(dateFormat)); parsers.addBinding().toInstance(new LocalDateParser(dateTimeFormatter)); parsers.addBinding().toInstance(new ZonedDateTimeParser(zonedDateTimeFormat)); parsers.addBinding().toInstance(new LocaleParser()); parsers.addBinding().toInstance(new StaticMethodParser("valueOf")); parsers.addBinding().toInstance(new StaticMethodParser("fromString")); parsers.addBinding().toInstance(new StaticMethodParser("forName")); parsers.addBinding().toInstance(new StringConstructorParser()); parsers.addBinding().toInstance(beanParser.orElseGet(() -> new BeanParser(false))); binder.bind(ParserExecutor.class).in(Singleton.class); /** override(able) renderer */ renderers.addBinding().toInstance(new DefaulErrRenderer()); renderers.addBinding().toInstance(BuiltinRenderer.text); binder.bind(HttpHandler.class).to(HttpHandlerImpl.class).in(Singleton.class); RequestScope requestScope = new RequestScope(); binder.bind(RequestScope.class).toInstance(requestScope); binder.bindScope(RequestScoped.class, requestScope); /** session manager */ binder.bind(Session.Definition.class) .toProvider(session(finalConfig.getConfig("session"), session)) .asEagerSingleton(); Object sstore = session.store(); if (cookieSession) { binder.bind(SessionManager.class).to(CookieSessionManager.class) .asEagerSingleton(); } else { binder.bind(SessionManager.class).to(ServerSessionManager.class).asEagerSingleton(); if (sstore instanceof Class) { binder.bind(Store.class).to((Class<? extends Store>) sstore) .asEagerSingleton(); } else { binder.bind(Store.class).toInstance((Store) sstore); } } binder.bind(Request.class).toProvider(Providers.outOfScope(Request.class)) .in(RequestScoped.class); binder.bind(Route.Chain.class).toProvider(Providers.outOfScope(Route.Chain.class)) .in(RequestScoped.class); binder.bind(Response.class).toProvider(Providers.outOfScope(Response.class)) .in(RequestScoped.class); /** server sent event */ binder.bind(Sse.class).toProvider(Providers.outOfScope(Sse.class)) .in(RequestScoped.class); binder.bind(Session.class).toProvider(Providers.outOfScope(Session.class)) .in(RequestScoped.class); /** def err */ ehandlers.addBinding().toInstance(new Err.DefHandler()); /** executors. */ executors.forEach(it -> it.accept(binder)); }; Injector injector = injectorFactory.apply(stage, joobyModule); if (apprefs != null) { apprefs.forEach(app -> app.injector = injector); apprefs.clear(); apprefs = null; } onStart.addAll(0, finalEnv.startTasks()); onStarted.addAll(0, finalEnv.startedTasks()); onStop.addAll(finalEnv.stopTasks()); // clear bag and freeze it this.bag.clear(); this.bag = ImmutableSet.of(); this.executors.clear(); this.executors = ImmutableList.of(); return injector; } private void xss(final Env env) { Escaper ufe = UrlEscapers.urlFragmentEscaper(); Escaper fpe = UrlEscapers.urlFormParameterEscaper(); Escaper pse = UrlEscapers.urlPathSegmentEscaper(); Escaper html = HtmlEscapers.htmlEscaper(); env.xss("urlFragment", ufe::escape) .xss("formParam", fpe::escape) .xss("pathSegment", pse::escape) .xss("html", html::escape); } private static Provider<Session.Definition> session(final Config $session, final Session.Definition session) { return () -> { // save interval session.saveInterval(session.saveInterval() .orElse($session.getDuration("saveInterval", TimeUnit.MILLISECONDS))); // build cookie Cookie.Definition source = session.cookie(); source.name(source.name() .orElse($session.getString("cookie.name"))); if (!source.comment().isPresent() && $session.hasPath("cookie.comment")) { source.comment($session.getString("cookie.comment")); } if (!source.domain().isPresent() && $session.hasPath("cookie.domain")) { source.domain($session.getString("cookie.domain")); } source.httpOnly(source.httpOnly() .orElse($session.getBoolean("cookie.httpOnly"))); Object maxAge = $session.getAnyRef("cookie.maxAge"); if (maxAge instanceof String) { maxAge = $session.getDuration("cookie.maxAge", TimeUnit.SECONDS); } source.maxAge(source.maxAge() .orElse(((Number) maxAge).intValue())); source.path(source.path() .orElse($session.getString("cookie.path"))); source.secure(source.secure() .orElse($session.getBoolean("cookie.secure"))); return session; }; } private static Throwing.Consumer<? super Object> bindService(Logger log, final Set<Object> src, final Config conf, final Env env, final RouteMetadata rm, final Binder binder, final Multibinder<Route.Definition> definitions, final Multibinder<WebSocket.Definition> sockets, final Multibinder<Err.Handler> ehandlers, final Multibinder<Parser> parsers, final Multibinder<Renderer> renderers, final Set<Object> routeClasses, final boolean caseSensitiveRouting) { return it -> { if (it instanceof Jooby.Module) { int from = src.size(); install(log, (Jooby.Module) it, env, conf, binder); int to = src.size(); // collect any route a module might add if (to > from) { List<Object> elements = normalize(new ArrayList<>(src).subList(from, to), env, rm, caseSensitiveRouting); for (Object e : elements) { bindService(log, src, conf, env, rm, binder, definitions, sockets, ehandlers, parsers, renderers, routeClasses, caseSensitiveRouting).accept(e); } } } else if (it instanceof Route.Definition) { Route.Definition rdef = (Definition) it; Route.Filter h = rdef.filter(); if (h instanceof Route.MethodHandler) { Class<?> routeClass = ((Route.MethodHandler) h).implementingClass(); if (routeClasses.add(routeClass)) { binder.bind(routeClass); } definitions.addBinding().toInstance(rdef); } else { definitions.addBinding().toInstance(rdef); } } else if (it instanceof WebSocket.Definition) { sockets.addBinding().toInstance((WebSocket.Definition) it); } else if (it instanceof Parser) { parsers.addBinding().toInstance((Parser) it); } else if (it instanceof Renderer) { renderers.addBinding().toInstance((Renderer) it); } else { ehandlers.addBinding().toInstance((Err.Handler) it); } }; } private static List<Config> modconf(final Collection<Object> bag) { return bag.stream() .filter(it -> it instanceof Jooby.Module) .map(it -> ((Jooby.Module) it).config()) .filter(c -> !c.isEmpty()) .collect(Collectors.toList()); } /** * Test if the application is up and running. * * @return True if the application is up and running. */ public boolean isStarted() { return started.get(); } /** * Stop the application, fire the {@link #onStop(Throwing.Runnable)} event and shutdown the * web server. * * Stop listeners run in the order they were added: * * <pre>{@code * { * * onStop(() -> System.out.println("first")); * * onStop(() -> System.out.println("second")); * * ... * } * }</pre> * * */ public void stop() { if (started.compareAndSet(true, false)) { Logger log = logger(this); fireStop(this, log, onStop); if (injector != null) { try { injector.getInstance(Server.class).stop(); } catch (Throwable ex) { log.debug("server.stop() resulted in exception", ex); } } injector = null; log.info("Stopped"); } } private static void fireStop(final Jooby app, final Logger log, final List<Throwing.Consumer<Registry>> onStop) { // stop services onStop.forEach(c -> Try.run(() -> c.accept(app)) .onFailure(x -> log.error("shutdown of {} resulted in error", c, x))); } /** * Build configuration properties, it configure system, app and modules properties. * * @param source Source config to use. * @param args Args conf. * @param modules List of modules. * @return A configuration properties ready to use. */ private Config buildConfig(final Config source, final Config args, final List<Config> modules) { // normalize tmpdir Config system = ConfigFactory.systemProperties(); Config tmpdir = source.hasPath("java.io.tmpdir") ? source : system; // system properties system = system // file encoding got corrupted sometimes, override it. .withValue("file.encoding", fromAnyRef(System.getProperty("file.encoding"))) .withValue("java.io.tmpdir", fromAnyRef(Paths.get(tmpdir.getString("java.io.tmpdir")).normalize().toString())); // set module config Config moduleStack = ConfigFactory.empty(); for (Config module : ImmutableList.copyOf(modules).reverse()) { moduleStack = moduleStack.withFallback(module); } String env = Arrays.asList(system, args, source).stream() .filter(it -> it.hasPath("application.env")) .findFirst() .map(c -> c.getString("application.env")) .orElse("dev"); String cpath = Arrays.asList(system, args, source).stream() .filter(it -> it.hasPath("application.path")) .findFirst() .map(c -> c.getString("application.path")) .orElse("/"); Config envconf = envConf(source, env); // application.[env].conf -> application.conf Config conf = envconf.withFallback(source); return system .withFallback(args) .withFallback(conf) .withFallback(moduleStack) .withFallback(MediaType.types) .withFallback(defaultConfig(conf, Route.normalize(cpath))) .resolve(); } /** * Build a conf from arguments. * * @param args Application arguments. * @return A conf. */ static Config args(final String[] args) { if (args == null || args.length == 0) { return ConfigFactory.empty(); } Map<String, String> conf = new HashMap<>(); for (String arg : args) { String[] values = arg.split("="); String name; String value; if (values.length == 2) { name = values[0]; value = values[1]; } else { name = "application.env"; value = values[0]; } if (name.indexOf(".") == -1) { conf.put("application." + name, value); } conf.put(name, value); } return ConfigFactory.parseMap(conf, "args"); } /** * Build a env config: <code>[application].[env].[conf]</code>. * Stack looks like * * <pre> * (file://[origin].[env].[conf])? * (cp://[origin].[env].[conf])? * file://application.[env].[conf] * /application.[env].[conf] * </pre> * * @param source App source to use. * @param env Application env. * @return A config env. */ private Config envConf(final Config source, final String env) { String name = Optional.ofNullable(this.confname).orElse(source.origin().resource()); Config result = ConfigFactory.empty(); if (name != null) { // load [resource].[env].[ext] int dot = name.lastIndexOf('.'); name = name.substring(0, dot); } else { name = "application"; } String envconfname = name + "." + env + ".conf"; Config envconf = fileConfig(envconfname); Config appconf = fileConfig(name + ".conf"); return result // file system: .withFallback(envconf) .withFallback(appconf) // classpath: .withFallback(ConfigFactory.parseResources(envconfname)); } /** * Config from file system. * * @param fname A file name. * @return A config for the file name. */ static Config fileConfig(final String fname) { // TODO: sanitization of arguments File dir = new File(System.getProperty("user.dir")); // TODO: sanitization of arguments File froot = new File(dir, fname); if (froot.exists()) { return ConfigFactory.parseFile(froot); } else { // TODO: sanitization of arguments File fconfig = new File(new File(dir, "conf"), fname); if (fconfig.exists()) { return ConfigFactory.parseFile(fconfig); } } return ConfigFactory.empty(); } /** * Build default application.* properties. * * @param conf A source config. * @param cpath Application path. * @return default properties. */ private Config defaultConfig(final Config conf, final String cpath) { String ns = Optional.ofNullable(getClass().getPackage()) .map(Package::getName) .orElse("default." + getClass().getName()); String[] parts = ns.split("\\."); String appname = parts[parts.length - 1]; // locale final List<Locale> locales; if (!conf.hasPath("application.lang")) { locales = Optional.ofNullable(this.languages) .map(langs -> LocaleUtils.parse(Joiner.on(",").join(langs))) .orElse(ImmutableList.of(Locale.getDefault())); } else { locales = LocaleUtils.parse(conf.getString("application.lang")); } Locale locale = locales.iterator().next(); String lang = locale.toLanguageTag(); // time zone final String tz; if (!conf.hasPath("application.tz")) { tz = Optional.ofNullable(zoneId).orElse(ZoneId.systemDefault()).getId(); } else { tz = conf.getString("application.tz"); } // number format final String nf; if (!conf.hasPath("application.numberFormat")) { nf = Optional.ofNullable(numberFormat) .orElseGet(() -> ((DecimalFormat) DecimalFormat.getInstance(locale)).toPattern()); } else { nf = conf.getString("application.numberFormat"); } int processors = Runtime.getRuntime().availableProcessors(); String version = Optional.ofNullable(getClass().getPackage()) .map(Package::getImplementationVersion) .filter(Objects::nonNull) .orElse("0.0.0"); Config defs = ConfigFactory.parseResources(Jooby.class, "jooby.conf") .withValue("contextPath", fromAnyRef(cpath.equals("/") ? "" : cpath)) .withValue("application.name", fromAnyRef(appname)) .withValue("application.version", fromAnyRef(version)) .withValue("application.class", fromAnyRef(classname)) .withValue("application.ns", fromAnyRef(ns)) .withValue("application.lang", fromAnyRef(lang)) .withValue("application.tz", fromAnyRef(tz)) .withValue("application.numberFormat", fromAnyRef(nf)) .withValue("server.http2.enabled", fromAnyRef(http2)) .withValue("runtime.processors", fromAnyRef(processors)) .withValue("runtime.processors-plus1", fromAnyRef(processors + 1)) .withValue("runtime.processors-plus2", fromAnyRef(processors + 2)) .withValue("runtime.processors-x2", fromAnyRef(processors * 2)) .withValue("runtime.processors-x4", fromAnyRef(processors * 4)) .withValue("runtime.processors-x8", fromAnyRef(processors * 8)) .withValue("runtime.concurrencyLevel", fromAnyRef(Math.max(4, processors))) .withValue("server.threads.Min", fromAnyRef(Math.max(4, processors))) .withValue("server.threads.Max", fromAnyRef(Math.max(32, processors * 8))); if (charset != null) { defs = defs.withValue("application.charset", fromAnyRef(charset.name())); } if (port != null) { defs = defs.withValue("application.port", fromAnyRef(port)); } if (securePort != null) { defs = defs.withValue("application.securePort", fromAnyRef(securePort)); } if (dateFormat != null) { defs = defs.withValue("application.dateFormat", fromAnyRef(dateFormat)); } return defs; } /** * Install a {@link Jooby.Module}. * * @param log Logger. * @param module The module to install. * @param env Application env. * @param config The configuration object. * @param binder A Guice binder. * @throws Throwable If module bootstrap fails. */ private static void install(final Logger log, final Jooby.Module module, final Env env, final Config config, final Binder binder) throws Throwable { module.configure(env, config, binder); try { binder.install(ProviderMethodsModule.forObject(module)); } catch (NoClassDefFoundError x) { // Allow dynamic linking of optional dependencies (required by micrometer module), we ignore // missing classes here, if there is a missing class Jooby is going to fails early (not here) log.debug("ignoring class not found from guice provider method", x); } } /** * Bind a {@link Config} and make it available for injection. Each property of the config is also * binded it and ready to be injected with {@link javax.inject.Named}. * * @param binder Guice binder. * @param config App config. */ @SuppressWarnings("unchecked") private void bindConfig(final Binder binder, final Config config) { // root nodes traverse(binder, "", config.root()); // terminal nodes for (Entry<String, ConfigValue> entry : config.entrySet()) { String name = entry.getKey(); Named named = Names.named(name); Object value = entry.getValue().unwrapped(); if (value instanceof List) { List<Object> values = (List<Object>) value; Type listType = values.size() == 0 ? String.class : Types.listOf(values.iterator().next().getClass()); Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name)); binder.bind(key).toInstance(values); } else { binder.bindConstant().annotatedWith(named).to(value.toString()); } } // bind config binder.bind(Config.class).toInstance(config); } private static void traverse(final Binder binder, final String p, final ConfigObject root) { root.forEach((n, v) -> { if (v instanceof ConfigObject) { ConfigObject child = (ConfigObject) v; String path = p + n; Named named = Names.named(path); binder.bind(Config.class).annotatedWith(named).toInstance(child.toConfig()); traverse(binder, path + ".", child); } }); } private static Predicate<String> envpredicate(final String candidate) { return env -> env.equalsIgnoreCase(candidate) || candidate.equals("*"); } static String logback(final Config conf) { // Avoid warning message from logback when multiples files are present String logback; if (conf.hasPath("logback.configurationFile")) { logback = conf.getString("logback.configurationFile"); } else { String env = conf.hasPath("application.env") ? conf.getString("application.env") : null; ImmutableList.Builder<File> files = ImmutableList.builder(); // TODO: sanitization of arguments File userdir = new File(System.getProperty("user.dir")); File confdir = new File(userdir, "conf"); if (env != null) { files.add(new File(userdir, "logback." + env + ".xml")); files.add(new File(confdir, "logback." + env + ".xml")); } files.add(new File(userdir, "logback.xml")); files.add(new File(confdir, "logback.xml")); logback = files.build() .stream() .filter(File::exists) .map(File::getAbsolutePath) .findFirst() .orElseGet(() -> { return Optional.ofNullable(Jooby.class.getResource("/logback." + env + ".xml")) .map(Objects::toString) .orElse("logback.xml"); }); } return logback; } private static Logger logger(final Jooby app) { return LoggerFactory.getLogger(app.getClass()); } private Route.AssetDefinition configureAssetHandler(final Route.AssetDefinition handler) { onStart(r -> { Config conf = r.require(Config.class); handler .cdn(conf.getString("assets.cdn")) .lastModified(conf.getBoolean("assets.lastModified")) .etag(conf.getBoolean("assets.etag")) .maxAge(conf.getString("assets.cache.maxAge")); }); return handler; } /** * Class name is this, except for script bootstrap. * * @param name Default classname. * @return Classname. */ private String classname(String name) { if (name.equals(Jooby.class.getName()) || name.equals("org.jooby.Kooby")) { return SourceProvider.INSTANCE.get() .map(StackTraceElement::getClassName) .orElse(name); } return name; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_0
crossvul-java_data_good_4471_0
/* * file: InputStreamHelper.java * author: Jon Iles * copyright: (c) Packwood Software 2016 * date: 06/06/2016 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.common; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipInputStream; /** * Helper methods for dealing with InputStreams. */ public class InputStreamHelper { /** * Copy the data from an InputStream to a temp file. * * @param inputStream data source * @param tempFileSuffix suffix to use for temp file * @return File instance */ public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException { FileOutputStream outputStream = null; try { File file = File.createTempFile("mpxj", tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } } /** * Expands a zip file input stream into a temporary directory. * * @param inputStream zip file input stream * @return File instance representing the temporary directory */ public static File writeZipStreamToTempDir(InputStream inputStream) throws IOException { File dir = FileHelper.createTempDir(); try { processZipStream(dir, inputStream); } catch (ZipException ex) { // Java doesn't support zip files with zero byte entries. // We could use a different library which does handle these zip files, but // I'm reluctant to add new dependencies just for this. Rather than // propagating the error, we'll just stop at this point and see if we // can make sense of anything we have extracted from the zip file so far. // For what it's worth I haven't come across a valid compressed schedule file // which includes zero bytes files. if (!ex.getMessage().equals("only DEFLATED entries can have EXT descriptor")) { throw ex; } } return dir; } /** * Expands a zip file input stream into a temporary directory. * * @param dir temporary directory * @param inputStream zip file input stream */ private static void processZipStream(File dir, InputStream inputStream) throws IOException { String canonicalDestinationDirPath = dir.getCanonicalPath(); ZipInputStream zip = new ZipInputStream(inputStream); while (true) { ZipEntry entry = zip.getNextEntry(); if (entry == null) { break; } File file = new File(dir, entry.getName()); // https://snyk.io/research/zip-slip-vulnerability String canonicalDestinationFile = file.getCanonicalPath(); if (!canonicalDestinationFile.startsWith(canonicalDestinationDirPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + entry.getName()); } if (entry.isDirectory()) { FileHelper.mkdirsQuietly(file); continue; } File parent = file.getParentFile(); if (parent != null) { FileHelper.mkdirsQuietly(parent); } FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = zip.read(bytes)) >= 0) { fos.write(bytes, 0, length); } fos.close(); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4471_0
crossvul-java_data_bad_688_1
package spark.embeddedserver.jetty; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.After; import org.junit.Test; import spark.embeddedserver.EmbeddedServer; import spark.route.Routes; import spark.staticfiles.StaticFilesConfiguration; import static org.mockito.Mockito.*; public class EmbeddedJettyFactoryTest { private EmbeddedServer embeddedServer; @Test public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withThreadPool() throws Exception { final QueuedThreadPool threadPool = new QueuedThreadPool(100); final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool)); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 0,0,0); verify(jettyServerFactory, times(1)).create(threadPool); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); } @After public void tearDown() throws Exception { if(embeddedServer != null) embeddedServer.extinguish(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_688_1
crossvul-java_data_good_4612_2
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby.handlers; import com.google.common.base.Strings; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import org.jooby.Asset; import org.jooby.Err; import org.jooby.Jooby; import org.jooby.MediaType; import org.jooby.Request; import org.jooby.Response; import org.jooby.Route; import org.jooby.Status; import org.jooby.funzy.Throwing; import org.jooby.funzy.Try; import org.jooby.internal.URLAsset; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.time.Duration; import java.util.Date; import java.util.Map; import static java.util.Objects.requireNonNull; /** * Serve static resources, via {@link Jooby#assets(String)} or variants. * * <h1>e-tag support</h1> * <p> * It generates <code>ETag</code> headers using {@link Asset#etag()}. It handles * <code>If-None-Match</code> header automatically. * </p> * <p> * <code>ETag</code> handling is enabled by default. If you want to disabled etag support * {@link #etag(boolean)}. * </p> * * <h1>modified since support</h1> * <p> * It generates <code>Last-Modified</code> header using {@link Asset#lastModified()}. It handles * <code>If-Modified-Since</code> header automatically. * </p> * * <h1>CDN support</h1> * <p> * Asset can be serve from a content delivery network (a.k.a cdn). All you have to do is to set the * <code>assets.cdn</code> property. * </p> * * <pre> * assets.cdn = "http://d7471vfo50fqt.cloudfront.net" * </pre> * * <p> * Resolved assets are redirected to the cdn. * </p> * * @author edgar * @since 0.1.0 */ public class AssetHandler implements Route.Handler { private interface Loader { URL getResource(String name); } private static final Throwing.Function<String, String> prefix = prefix().memoized(); private Throwing.Function2<Request, String, String> fn; private Loader loader; private String cdn; private boolean etag = true; private long maxAge = -1; private boolean lastModified = true; private int statusCode = 404; private String location; private Path basedir; private ClassLoader classLoader; /** * <p> * Creates a new {@link AssetHandler}. The handler accepts a location pattern, that serve for * locating the static resource. * </p> * * Given <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param pattern Pattern to locate static resources. * @param loader The one who load the static resources. */ public AssetHandler(final String pattern, final ClassLoader loader) { this.location = Route.normalize(pattern); this.basedir = Paths.get("public"); this.classLoader = loader; } /** * <p> * Creates a new {@link AssetHandler}. The handler accepts a location pattern, that serve for * locating the static resource. * </p> * * Given <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param basedir Base directory. */ public AssetHandler(final Path basedir) { this.location = "/{0}"; this.basedir = basedir; this.classLoader = getClass().getClassLoader(); } /** * <p> * Creates a new {@link AssetHandler}. The location pattern can be one of. * </p> * * Given <code>/</code> like in <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>/assets</code> like in <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>/META-INF/resources/webjars/{0}</code> like in * <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param pattern Pattern to locate static resources. */ public AssetHandler(final String pattern) { this.location = Route.normalize(pattern); this.basedir = Paths.get("public"); this.classLoader = getClass().getClassLoader(); } /** * @param etag Turn on/off etag support. * @return This handler. */ public AssetHandler etag(final boolean etag) { this.etag = etag; return this; } /** * @param enabled Turn on/off last modified support. * @return This handler. */ public AssetHandler lastModified(final boolean enabled) { this.lastModified = enabled; return this; } /** * @param cdn If set, every resolved asset will be serve from it. * @return This handler. */ public AssetHandler cdn(final String cdn) { this.cdn = Strings.emptyToNull(cdn); return this; } /** * @param maxAge Set the cache header max-age value. * @return This handler. */ public AssetHandler maxAge(final Duration maxAge) { return maxAge(maxAge.getSeconds()); } /** * @param maxAge Set the cache header max-age value in seconds. * @return This handler. */ public AssetHandler maxAge(final long maxAge) { this.maxAge = maxAge; return this; } /** * Set the route definition and initialize the handler. * * @param route Route definition. * @return This handler. */ public AssetHandler setRoute(final Route.AssetDefinition route) { String prefix; boolean rootLocation = location.equals("/") || location.equals("/{0}"); if (rootLocation) { String pattern = route.pattern(); int i = pattern.indexOf("/*"); if (i > 0) { prefix = pattern.substring(0, i + 1); } else { prefix = pattern; } } else { int i = location.indexOf("{"); if (i > 0) { prefix = location.substring(0, i); } else { /// TODO: review what we have here prefix = location; } } if (prefix.startsWith("/")) { prefix = prefix.substring(1); } if (prefix.isEmpty() && rootLocation) { throw new IllegalArgumentException( "For security reasons root classpath access is not allowed. Map your static resources " + "using a prefix like: assets(static/**); or use a location classpath prefix like: " + "assets(/, /static/{0})"); } init(prefix, location, basedir, classLoader); return this; } /** * Parse value as {@link Duration}. If the value is already a number then it uses as seconds. * Otherwise, it parse expressions like: 8m, 1h, 365d, etc... * * @param maxAge Set the cache header max-age value in seconds. * @return This handler. */ public AssetHandler maxAge(final String maxAge) { Try.apply(() -> Long.parseLong(maxAge)) .recover(x -> ConfigFactory.empty() .withValue("v", ConfigValueFactory.fromAnyRef(maxAge)) .getDuration("v") .getSeconds()) .onSuccess(this::maxAge); return this; } /** * Indicates what to do when an asset is missing (not resolved). Default action is to resolve them * as <code>404 (NOT FOUND)</code> request. * * If you specify a status code &lt;= 0, missing assets are ignored and the next handler on pipeline * will be executed. * * @param statusCode HTTP code or 0. * @return This handler. */ public AssetHandler onMissing(final int statusCode) { this.statusCode = statusCode; return this; } @Override public void handle(final Request req, final Response rsp) throws Throwable { String path = req.path(); URL resource = resolve(req, path); if (resource != null) { String localpath = resource.getPath(); int jarEntry = localpath.indexOf("!/"); if (jarEntry > 0) { localpath = localpath.substring(jarEntry + 2); } URLAsset asset = new URLAsset(resource, path, MediaType.byPath(localpath).orElse(MediaType.octetstream)); if (asset.exists()) { // cdn? if (cdn != null) { String absUrl = cdn + path; rsp.redirect(absUrl); rsp.end(); } else { doHandle(req, rsp, asset); } } } else if (statusCode > 0) { throw new Err(statusCode); } } private void doHandle(final Request req, final Response rsp, final Asset asset) throws Throwable { // handle etag if (this.etag) { String etag = asset.etag(); boolean ifnm = req.header("If-None-Match").toOptional() .map(etag::equals) .orElse(false); if (ifnm) { rsp.header("ETag", etag).status(Status.NOT_MODIFIED).end(); return; } rsp.header("ETag", etag); } // Handle if modified since if (this.lastModified) { long lastModified = asset.lastModified(); if (lastModified > 0) { boolean ifm = req.header("If-Modified-Since").toOptional(Long.class) .map(ifModified -> lastModified / 1000 <= ifModified / 1000) .orElse(false); if (ifm) { rsp.status(Status.NOT_MODIFIED).end(); return; } rsp.header("Last-Modified", new Date(lastModified)); } } // cache max-age if (maxAge > 0) { rsp.header("Cache-Control", "max-age=" + maxAge); } send(req, rsp, asset); } /** * Send an asset to the client. * * @param req Request. * @param rsp Response. * @param asset Resolve asset. * @throws Exception If send fails. */ protected void send(final Request req, final Response rsp, final Asset asset) throws Throwable { rsp.send(asset); } private URL resolve(final Request req, final String path) throws Throwable { String target = fn.apply(req, path); return resolve(target); } /** * Resolve a path as a {@link URL}. * * @param path Path of resource to resolve. * @return A URL or <code>null</code> for unresolved resource. * @throws Exception If something goes wrong. */ protected URL resolve(final String path) throws Exception { return loader.getResource(path); } private void init(final String classPathPrefix, final String location, final Path basedir, final ClassLoader loader) { requireNonNull(loader, "Resource loader is required."); this.fn = location.equals("/") ? (req, p) -> prefix.apply(p) : (req, p) -> MessageFormat.format(prefix.apply(location), vars(req)); this.loader = loader(basedir, classpathLoader(classPathPrefix, classLoader)); } private static Object[] vars(final Request req) { Map<Object, String> vars = req.route().vars(); return vars.values().toArray(new Object[vars.size()]); } private static Loader loader(final Path basedir, Loader classpath) { if (basedir != null && Files.exists(basedir)) { return name -> { Path path = basedir.resolve(name).normalize(); if (Files.exists(path) && path.startsWith(basedir)) { try { return path.toUri().toURL(); } catch (MalformedURLException x) { // shh } } return classpath.getResource(name); }; } return classpath; } private static Loader classpathLoader(String prefix, ClassLoader classloader) { return name -> { String safePath = safePath(name); if (safePath.startsWith(prefix)) { URL resource = classloader.getResource(safePath); return resource; } return null; }; } private static String safePath(String name) { if (name.indexOf("./") > 0) { Path path = toPath(name.split("/")).normalize(); return toStringPath(path); } return name; } private static String toStringPath(Path path) { StringBuilder buffer = new StringBuilder(); for (Path segment : path) { buffer.append("/").append(segment); } return buffer.substring(1); } private static Path toPath(String[] segments) { Path path = Paths.get(segments[0]); for (int i = 1; i < segments.length; i++) { path = path.resolve(segments[i]); } return path; } private static Throwing.Function<String, String> prefix() { return p -> p.substring(1); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_2
crossvul-java_data_bad_489_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_489_1
crossvul-java_data_good_689_1
package spark.embeddedserver.jetty; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.After; import org.junit.Test; import spark.embeddedserver.EmbeddedServer; import spark.route.Routes; import spark.staticfiles.StaticFilesConfiguration; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class EmbeddedJettyFactoryTest { private EmbeddedServer embeddedServer; @Test public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6757, null, 100, 10, 10000); verify(jettyServerFactory, times(1)).create(100, 10, 10000); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withThreadPool() throws Exception { final QueuedThreadPool threadPool = new QueuedThreadPool(100); final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool)); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6758, null, 0, 0, 0); verify(jettyServerFactory, times(1)).create(threadPool); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6759, null, 100, 10, 10000); verify(jettyServerFactory, times(1)).create(100, 10, 10000); verifyNoMoreInteractions(jettyServerFactory); } @After public void tearDown() throws Exception { if (embeddedServer != null) { embeddedServer.extinguish(); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_689_1
crossvul-java_data_good_1883_2
package eu.hinsch.spring.boot.actuator.logview; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.ui.Model; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; /** * Created by lh on 23/02/15. */ public class LogViewEndpoint implements MvcEndpoint{ private final List<FileProvider> fileProviders; private final Configuration freemarkerConfig; private final String loggingPath; private final List<String> stylesheets; public LogViewEndpoint(String loggingPath, List<String> stylesheets) { this.loggingPath = loggingPath; this.stylesheets = stylesheets; fileProviders = asList(new FileSystemFileProvider(), new ZipArchiveFileProvider(), new TarGzArchiveFileProvider()); freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); } @RequestMapping public void redirect(HttpServletResponse response) throws IOException { response.sendRedirect("log/"); } @RequestMapping("/") @ResponseBody public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { Path currentFolder = loggingPath(base); securityCheck(currentFolder, null); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); } private FileProvider getFileProvider(Path folder) { return fileProviders.stream() .filter(provider -> provider.canHandle(folder)) .findFirst() .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString())); } private String getParent(Path loggingPath) { Path basePath = loggingPath(null); String parent = ""; if (!basePath.toString().equals(loggingPath.toString())) { parent = loggingPath.getParent().toString(); if (parent.startsWith(basePath.toString())) { parent = parent.substring(basePath.toString().length()); } } return parent; } private Path loggingPath(String base) { return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath); } private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) { Comparator<FileEntry> comparator = null; switch (sortBy) { case FILENAME: comparator = (a, b) -> a.getFilename().compareTo(b.getFilename()); break; case SIZE: comparator = (a, b) -> Long.compare(a.getSize(), b.getSize()); break; case MODIFIED: comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis()); break; } List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList()); if (desc) { Collections.reverse(sortedFiles); } return sortedFiles; } @RequestMapping("/view") public void view(@RequestParam String filename, @RequestParam(required = false) String base, @RequestParam(required = false) Integer tailLines, HttpServletResponse response) throws IOException { Path path = loggingPath(base); securityCheck(path, filename); response.setContentType(MediaType.TEXT_PLAIN_VALUE); FileProvider fileProvider = getFileProvider(path); if (tailLines != null) { fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines); } else { fileProvider.streamContent(path, filename, response.getOutputStream()); } } @RequestMapping("/search") public void search(@RequestParam String term, HttpServletResponse response) throws IOException { Path folder = loggingPath(null); List<FileEntry> files = getFileProvider(folder).getFileEntries(folder); List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false); response.setContentType(MediaType.TEXT_PLAIN_VALUE); ServletOutputStream outputStream = response.getOutputStream(); sortedFiles.stream() .filter(file -> file.getFileType().equals(FileType.FILE)) .forEach(file -> searchAndStreamFile(file, term, outputStream)); } private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) { Path folder = loggingPath(null); try { List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename()))) .stream() .filter(line -> line.contains(term)) .map(line -> "[" + fileEntry.getFilename() + "] " + line) .collect(toList()); for (String line : lines) { outputStream.write(line.getBytes()); outputStream.write(System.lineSeparator().getBytes()); } } catch (IOException e) { throw new RuntimeException("error reading file", e); } } private void securityCheck(Path base, String filename) { try { String canonicalLoggingPath = (filename != null ? new File(base.toFile().toString(), filename) : new File(base.toFile().toString())).getCanonicalPath(); String baseCanonicalPath = new File(loggingPath).getCanonicalPath(); String errorMessage = "File " + base.toString() + "/" + filename + " may not be located outside base path " + loggingPath; Assert.isTrue(canonicalLoggingPath.startsWith(baseCanonicalPath), errorMessage); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String getPath() { return "/log"; } @Override public boolean isSensitive() { return true; } @Override public Class<? extends Endpoint> getEndpointType() { return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_1883_2
crossvul-java_data_good_256_0
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.application.applicationimpl; import static com.sun.faces.application.ApplicationImpl.THIS_LIBRARY; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.DateTimeConverterUsesSystemTimezone; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.RegisterConverterPropertyEditors; import static com.sun.faces.util.Util.isEmpty; import static com.sun.faces.util.Util.loadClass; import static com.sun.faces.util.Util.notNull; import static com.sun.faces.util.Util.notNullNamedObject; import static java.beans.Introspector.getBeanInfo; import static java.beans.PropertyEditorManager.findEditor; import static java.text.MessageFormat.format; import static java.util.Collections.unmodifiableMap; import static java.util.logging.Level.FINE; import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; import static javax.faces.application.Resource.COMPONENT_RESOURCE_KEY; import static javax.faces.component.UIComponent.ATTRS_WITH_DECLARED_DEFAULT_VALUES; import static javax.faces.component.UIComponent.BEANINFO_KEY; import static javax.faces.component.UIComponent.COMPOSITE_COMPONENT_TYPE_KEY; import java.beans.BeanDescriptor; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.enterprise.inject.spi.BeanManager; import javax.faces.FacesException; import javax.faces.application.Application; import javax.faces.application.Resource; import javax.faces.component.UIComponent; import javax.faces.component.behavior.Behavior; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.DateTimeConverter; import javax.faces.el.ValueBinding; import javax.faces.render.RenderKit; import javax.faces.render.Renderer; import javax.faces.validator.Validator; import javax.faces.view.ViewDeclarationLanguage; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.application.ConverterPropertyEditorFactory; import com.sun.faces.application.ViewMemberInstanceFactoryMetadataMap; import com.sun.faces.cdi.CdiUtils; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.MessageUtils; import com.sun.faces.util.ReflectionUtils; import com.sun.faces.util.Util; public class InstanceFactory { // Log instance for this class private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger(); private static final String CONTEXT = "context"; private static final String COMPONENT_EXPRESSION = "componentExpression"; private static final String COMPONENT_TYPE = "componentType"; private static final String COMPONENT_CLASS = "componentClass"; private static final Map<String, Class<?>[]> STANDARD_CONV_ID_TO_TYPE_MAP = new HashMap<>(8, 1.0f); private static final Map<Class<?>, String> STANDARD_TYPE_TO_CONV_ID_MAP = new HashMap<>(16, 1.0f); static { STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Byte", new Class[] { Byte.TYPE, Byte.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Boolean", new Class[] { Boolean.TYPE, Boolean.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Character", new Class[] { Character.TYPE, Character.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Short", new Class[] { Short.TYPE, Short.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Integer", new Class[] { Integer.TYPE, Integer.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Long", new Class[] { Long.TYPE, Long.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Float", new Class[] { Float.TYPE, Float.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Double", new Class[] { Double.TYPE, Double.class }); for (Map.Entry<String, Class<?>[]> entry : STANDARD_CONV_ID_TO_TYPE_MAP.entrySet()) { Class<?>[] types = entry.getValue(); String key = entry.getKey(); for (Class<?> clazz : types) { STANDARD_TYPE_TO_CONV_ID_MAP.put(clazz, key); } } } private final String[] STANDARD_BY_TYPE_CONVERTER_CLASSES = { "java.math.BigDecimal", "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Double", "java.lang.Float", "java.lang.Integer", "java.lang.Long", "java.lang.Short", "java.lang.Enum" }; private Map<Class<?>, Object> converterTypeMap; private boolean registerPropertyEditors; private boolean passDefaultTimeZone; private TimeZone systemTimeZone; private static final class ComponentResourceClassNotFound{} // // These four maps store store "identifier" | "class name" // mappings. // private ViewMemberInstanceFactoryMetadataMap<String, Object> componentMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> behaviorMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> converterIdMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> validatorMap; private Set<String> defaultValidatorIds; private volatile Map<String, String> defaultValidatorInfo; private final ApplicationAssociate associate; private Version version; /** * Stores the bean manager. */ private BeanManager beanManager; public InstanceFactory(ApplicationAssociate applicationAssociate) { this.associate = applicationAssociate; version = new Version(); componentMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); converterIdMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); converterTypeMap = new ConcurrentHashMap<>(); validatorMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); defaultValidatorIds = new LinkedHashSet<>(); behaviorMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); WebConfiguration webConfig = WebConfiguration.getInstance(FacesContext.getCurrentInstance().getExternalContext()); registerPropertyEditors = webConfig.isOptionEnabled(RegisterConverterPropertyEditors); passDefaultTimeZone = webConfig.isOptionEnabled(DateTimeConverterUsesSystemTimezone); if (passDefaultTimeZone) { systemTimeZone = TimeZone.getDefault(); } } /** * @see javax.faces.application.Application#addComponent(java.lang.String, java.lang.String) */ public void addComponent(String componentType, String componentClass) { notNull(COMPONENT_TYPE, componentType); notNull(COMPONENT_CLASS, componentClass); if (LOGGER.isLoggable(FINE) && componentMap.containsKey(componentType)) { LOGGER.log(FINE, "componentType {0} has already been registered. Replacing existing component class type {1} with {2}.", new Object[] { componentType, componentMap.get(componentType), componentClass }); } componentMap.put(componentType, componentClass); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("added component of type ''{0}'' and class ''{1}''", componentType, componentClass)); } } public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType) throws FacesException { notNull(COMPONENT_EXPRESSION, componentExpression); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(context, componentExpression, componentType, null, true); } public UIComponent createComponent(String componentType) throws FacesException { notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(FacesContext.getCurrentInstance(), componentType, null, true); } public UIComponent createComponent(FacesContext context, Resource componentResource, ExpressionFactory expressionFactory) throws FacesException { // RELEASE_PENDING (rlubke,driscoll) this method needs review. notNull(CONTEXT, context); notNull("componentResource", componentResource); UIComponent result = null; // Use the application defined in the FacesContext as we may be calling // overriden methods Application app = context.getApplication(); ViewDeclarationLanguage vdl = app.getViewHandler().getViewDeclarationLanguage(context, context.getViewRoot().getViewId()); BeanInfo componentMetadata = vdl.getComponentMetadata(context, componentResource); if (componentMetadata != null) { BeanDescriptor componentBeanDescriptor = componentMetadata.getBeanDescriptor(); // Step 1. See if the composite component author explicitly // gave a componentType as part of the composite component metadata ValueExpression valueExpression = (ValueExpression) componentBeanDescriptor.getValue(COMPOSITE_COMPONENT_TYPE_KEY); if (valueExpression != null) { String componentType = (String) valueExpression.getValue(context.getELContext()); if (!isEmpty(componentType)) { result = app.createComponent(componentType); } } } // Step 2. If that didn't work, if a script based resource can be // found for the scriptComponentResource, see if a component can be generated from it if (result == null) { Resource scriptComponentResource = vdl.getScriptComponentResource(context, componentResource); if (scriptComponentResource != null) { result = createComponentFromScriptResource(context, scriptComponentResource, componentResource); } } // Step 3. Use the libraryName of the resource as the java package // and use the resourceName as the class name. See // if a Java class can be loaded if (result == null) { String packageName = componentResource.getLibraryName(); String className = componentResource.getResourceName(); className = packageName + '.' + className.substring(0, className.lastIndexOf('.')); try { Class<?> clazz = (Class<?>) componentMap.get(className); if (clazz == null) { clazz = loadClass(className, this); } if (clazz != ComponentResourceClassNotFound.class) { if (!associate.isDevModeEnabled()) { componentMap.put(className, clazz); } result = (UIComponent) clazz.newInstance(); } } catch (ClassNotFoundException ex) { if (!associate.isDevModeEnabled()) { componentMap.put(className, ComponentResourceClassNotFound.class); } } catch (InstantiationException | IllegalAccessException | ClassCastException ie) { throw new FacesException(ie); } } // Step 4. Use javax.faces.NamingContainer as the component type if (result == null) { result = app.createComponent("javax.faces.NamingContainer"); } result.setRendererType("javax.faces.Composite"); Map<String, Object> attrs = result.getAttributes(); attrs.put(COMPONENT_RESOURCE_KEY, componentResource); attrs.put(BEANINFO_KEY, componentMetadata); associate.getAnnotationManager().applyComponentAnnotations(context, result); pushDeclaredDefaultValuesToAttributesMap(context, componentMetadata, attrs, result, expressionFactory); return result; } public UIComponent createComponent(FacesContext context, String componentType, String rendererType) { notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(context, componentType, rendererType, true); } public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType, String rendererType) { notNull(COMPONENT_EXPRESSION, componentExpression); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(context, componentExpression, componentType, rendererType, true); } public UIComponent createComponent(ValueBinding componentBinding, FacesContext context, String componentType) throws FacesException { notNull("componentBinding", componentBinding); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); Object result; boolean createOne = false; try { result = componentBinding.getValue(context); if (result != null) { createOne = !(result instanceof UIComponent); } if (result == null || createOne) { result = createComponentApplyAnnotations(context, componentType, null, false); componentBinding.setValue(context, result); } } catch (Exception ex) { throw new FacesException(ex); } return (UIComponent) result; } /** * @see javax.faces.application.Application#getComponentTypes() */ public Iterator<String> getComponentTypes() { return componentMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addBehavior(String, String) */ public void addBehavior(String behaviorId, String behaviorClass) { notNull("behaviorId", behaviorId); notNull("behaviorClass", behaviorClass); if (LOGGER.isLoggable(FINE) && behaviorMap.containsKey(behaviorId)) { LOGGER.log(FINE, "behaviorId {0} has already been registered. Replacing existing behavior class type {1} with {2}.", new Object[] { behaviorId, behaviorMap.get(behaviorId), behaviorClass }); } behaviorMap.put(behaviorId, behaviorClass); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("added behavior of type ''{0}'' class ''{1}''", behaviorId, behaviorClass)); } } /** * @see javax.faces.application.Application#createBehavior(String) */ public Behavior createBehavior(String behaviorId) throws FacesException { notNull("behaviorId", behaviorId); Behavior behavior = createCDIBehavior(behaviorId); if (behavior != null) { return behavior; } behavior = newThing(behaviorId, behaviorMap); notNullNamedObject(behavior, behaviorId, "jsf.cannot_instantiate_behavior_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created behavior of type ''{0}''", behaviorId)); } associate.getAnnotationManager().applyBehaviorAnnotations(FacesContext.getCurrentInstance(), behavior); return behavior; } /** * @see javax.faces.application.Application#getBehaviorIds() */ public Iterator<String> getBehaviorIds() { return behaviorMap.keySet().iterator(); } public void addConverter(String converterId, String converterClass) { notNull("converterId", converterId); notNull("converterClass", converterClass); if (LOGGER.isLoggable(FINE) && converterIdMap.containsKey(converterId)) { LOGGER.log(FINE, "converterId {0} has already been registered. Replacing existing converter class type {1} with {2}.", new Object[] { converterId, converterIdMap.get(converterId), converterClass }); } converterIdMap.put(converterId, converterClass); Class<?>[] types = STANDARD_CONV_ID_TO_TYPE_MAP.get(converterId); if (types != null) { for (Class<?> clazz : types) { // go directly against map to prevent cyclic method calls converterTypeMap.put(clazz, converterClass); addPropertyEditorIfNecessary(clazz); } } if (LOGGER.isLoggable(FINE)) { LOGGER.fine(format("added converter of type ''{0}'' and class ''{1}''", converterId, converterClass)); } } /** * @see javax.faces.application.Application#addConverter(Class, String) */ public void addConverter(Class<?> targetClass, String converterClass) { notNull("targetClass", targetClass); notNull("converterClass", converterClass); String converterId = STANDARD_TYPE_TO_CONV_ID_MAP.get(targetClass); if (converterId != null) { addConverter(converterId, converterClass); } else { if (LOGGER.isLoggable(FINE) && converterTypeMap.containsKey(targetClass)) { LOGGER.log(FINE, "converter target class {0} has already been registered. Replacing existing converter class type {1} with {2}.", new Object[] { targetClass.getName(), converterTypeMap.get(targetClass), converterClass }); } converterTypeMap.put(targetClass, converterClass); addPropertyEditorIfNecessary(targetClass); } if (LOGGER.isLoggable(FINE)) { LOGGER.fine(format("added converter of class type ''{0}''", converterClass)); } } /** * @see javax.faces.application.Application#createConverter(String) */ public Converter<?> createConverter(String converterId) { notNull("converterId", converterId); Converter<?> converter = createCDIConverter(converterId); if (converter != null) { return converter; } converter = newThing(converterId, converterIdMap); notNullNamedObject(converter, converterId, "jsf.cannot_instantiate_converter_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created converter of type ''{0}''", converterId)); } if (passDefaultTimeZone && converter instanceof DateTimeConverter) { ((DateTimeConverter) converter).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), converter); return converter; } /** * @see javax.faces.application.Application#createConverter(Class) */ public Converter createConverter(Class<?> targetClass) { Util.notNull("targetClass", targetClass); Converter returnVal = null; if (version.isJsf23()) { BeanManager beanManager = getBeanManager(); returnVal = CdiUtils.createConverter(beanManager, targetClass); if (returnVal != null) { return returnVal; } } returnVal = (Converter) newConverter(targetClass, converterTypeMap, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } // Search for converters registered to interfaces implemented by // targetClass Class<?>[] interfaces = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { returnVal = createConverterBasedOnClass(interfaces[i], targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } } } // Search for converters registered to superclasses of targetClass Class<?> superclass = targetClass.getSuperclass(); if (superclass != null) { returnVal = createConverterBasedOnClass(superclass, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } } return returnVal; } /** * @see javax.faces.application.Application#getConverterIds() */ public Iterator<String> getConverterIds() { return converterIdMap.keySet().iterator(); } /** * @see javax.faces.application.Application#getConverterTypes() */ public Iterator<Class<?>> getConverterTypes() { return converterTypeMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addValidator(String, String) */ public void addValidator(String validatorId, String validatorClass) { Util.notNull("validatorId", validatorId); Util.notNull("validatorClass", validatorClass); if (LOGGER.isLoggable(Level.FINE) && validatorMap.containsKey(validatorId)) { LOGGER.log(Level.FINE, "validatorId {0} has already been registered. Replacing existing validator class type {1} with {2}.", new Object[] { validatorId, validatorMap.get(validatorId), validatorClass }); } validatorMap.put(validatorId, validatorClass); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("added validator of type ''{0}'' class ''{1}''", validatorId, validatorClass)); } } /** * @see javax.faces.application.Application#createValidator(String) */ public Validator<?> createValidator(String validatorId) throws FacesException { notNull("validatorId", validatorId); Validator<?> validator = createCDIValidator(validatorId); if (validator != null) { return validator; } validator = newThing(validatorId, validatorMap); notNullNamedObject(validator, validatorId, "jsf.cannot_instantiate_validator_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created validator of type ''{0}''", validatorId)); } associate.getAnnotationManager().applyValidatorAnnotations(FacesContext.getCurrentInstance(), validator); return validator; } /** * @see javax.faces.application.Application#getValidatorIds() */ public Iterator<String> getValidatorIds() { return validatorMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addDefaultValidatorId(String) */ public synchronized void addDefaultValidatorId(String validatorId) { notNull("validatorId", validatorId); defaultValidatorInfo = null; defaultValidatorIds.add(validatorId); } /** * @see javax.faces.application.Application#getDefaultValidatorInfo() */ public Map<String, String> getDefaultValidatorInfo() { if (defaultValidatorInfo == null) { synchronized (this) { if (defaultValidatorInfo == null) { defaultValidatorInfo = new LinkedHashMap<>(); if (!defaultValidatorIds.isEmpty()) { for (String id : defaultValidatorIds) { String validatorClass; Object result = validatorMap.get(id); if (null != result) { if (result instanceof Class) { validatorClass = ((Class) result).getName(); } else { validatorClass = result.toString(); } defaultValidatorInfo.put(id, validatorClass); } } } } } defaultValidatorInfo = unmodifiableMap(defaultValidatorInfo); } return defaultValidatorInfo; } // --------------------------------------------------------- Private Methods private UIComponent createComponentFromScriptResource(FacesContext context, Resource scriptComponentResource, Resource componentResource) { UIComponent result = null; String className = scriptComponentResource.getResourceName(); int lastDot = className.lastIndexOf('.'); className = className.substring(0, lastDot); try { Class<?> componentClass = (Class<?>) componentMap.get(className); if (componentClass == null) { componentClass = Util.loadClass(className, this); } if (!associate.isDevModeEnabled()) { componentMap.put(className, componentClass); } result = (UIComponent) componentClass.newInstance(); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, null, ex); } } if (result != null) { // Make sure the resource is there for the annotation processor. result.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, componentResource); // In case there are any "this" references, // make sure they can be resolved. context.getAttributes().put(THIS_LIBRARY, componentResource.getLibraryName()); try { associate.getAnnotationManager().applyComponentAnnotations(context, result); } finally { context.getAttributes().remove(THIS_LIBRARY); } } return result; } /** * Leveraged by * {@link Application#createComponent(javax.el.ValueExpression, javax.faces.context.FacesContext, String)} * and * {@link Application#createComponent(javax.el.ValueExpression, javax.faces.context.FacesContext, String, String)}. * This method will apply any component and render annotations that may be present. */ private UIComponent createComponentApplyAnnotations(FacesContext ctx, ValueExpression componentExpression, String componentType, String rendererType, boolean applyAnnotations) { UIComponent c; try { c = (UIComponent) componentExpression.getValue(ctx.getELContext()); if (c == null) { c = this.createComponentApplyAnnotations(ctx, componentType, rendererType, applyAnnotations); componentExpression.setValue(ctx.getELContext(), c); } else if (applyAnnotations) { this.applyAnnotations(ctx, rendererType, c); } } catch (Exception ex) { throw new FacesException(ex); } return c; } /** * Leveraged by {@link Application#createComponent(String)} and * {@link Application#createComponent(javax.faces.context.FacesContext, String, String)} This * method will apply any component and render annotations that may be present. */ private UIComponent createComponentApplyAnnotations(FacesContext ctx, String componentType, String rendererType, boolean applyAnnotations) { UIComponent component; try { component = newThing(componentType, componentMap); } catch (Exception ex) { if (LOGGER.isLoggable(SEVERE)) { LOGGER.log(Level.SEVERE, "jsf.cannot_instantiate_component_error", componentType); } throw new FacesException(ex); } notNullNamedObject(component, componentType, "jsf.cannot_instantiate_component_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, MessageFormat.format("Created component with component type of ''{0}''", componentType)); } if (applyAnnotations) { applyAnnotations(ctx, rendererType, component); } return component; } /** * Process any annotations associated with this component/renderer. */ private void applyAnnotations(FacesContext ctx, String rendererType, UIComponent c) { if (c != null && ctx != null) { associate.getAnnotationManager().applyComponentAnnotations(ctx, c); if (rendererType != null) { RenderKit rk = ctx.getRenderKit(); Renderer r = null; if (rk != null) { r = rk.getRenderer(c.getFamily(), rendererType); if (r != null) { c.setRendererType(rendererType); associate.getAnnotationManager().applyRendererAnnotations(ctx, r, c); } } if ((rk == null || r == null) && LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Unable to create Renderer with rendererType {0} for component with component type of {1}", new Object[] { rendererType, c.getFamily() }); } } } } /** * <p> * PRECONDITIONS: the values in the Map are either Strings representing fully qualified java * class names, or java.lang.Class instances. * </p> * <p> * ALGORITHM: Look in the argument map for a value for the argument key. If found, if the value * is instanceof String, assume the String specifies a fully qualified java class name and * obtain the java.lang.Class instance for that String using Util.loadClass(). Replace the * String instance in the argument map with the Class instance. If the value is instanceof * Class, proceed. Assert that the value is either instanceof java.lang.Class or * java.lang.String. * </p> * <p> * Now that you have a java.lang.class, call its newInstance and return it as the result of this * method. * </p> * * @param key Used to look up the value in the <code>Map</code>. * @param map The <code>Map</code> that will be searched. * @return The new object instance. */ @SuppressWarnings("unchecked") private <T> T newThing(String key, ViewMemberInstanceFactoryMetadataMap<String, Object> map) { Object result; Class<?> clazz; Object value; value = map.get(key); if (value == null) { return null; } assert value instanceof String || value instanceof Class; if (value instanceof String) { String cValue = (String) value; try { clazz = Util.loadClass(cValue, value); if (!associate.isDevModeEnabled()) { map.put(key, clazz); } assert clazz != null; } catch (Exception e) { throw new FacesException(e.getMessage(), e); } } else { clazz = (Class) value; } try { result = clazz.newInstance(); } catch (Throwable t) { Throwable previousT; do { previousT = t; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Unable to load class: ", t); } } while (null != (t = t.getCause())); t = previousT; throw new FacesException(MessageUtils.getExceptionMessageString(MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, clazz.getName()), t); } return (T) result; } /* * This method makes it so that any cc:attribute elements that have a "default" attribute value * have those values pushed into the composite component attribute map so that programmatic * access (as opposed to EL access) will find the attribute values. * */ @SuppressWarnings("unchecked") private void pushDeclaredDefaultValuesToAttributesMap(FacesContext context, BeanInfo componentMetadata, Map<String, Object> attrs, UIComponent component, ExpressionFactory expressionFactory) { Collection<String> attributesWithDeclaredDefaultValues = null; PropertyDescriptor[] propertyDescriptors = null; for (PropertyDescriptor propertyDescriptor : componentMetadata.getPropertyDescriptors()) { Object defaultValue = propertyDescriptor.getValue("default"); if (defaultValue != null) { String key = propertyDescriptor.getName(); boolean isLiteralText = false; if (defaultValue instanceof ValueExpression) { isLiteralText = ((ValueExpression) defaultValue).isLiteralText(); if (isLiteralText) { defaultValue = ((ValueExpression) defaultValue).getValue(context.getELContext()); } } // Ensure this attribute is not a method-signature. method-signature // declared default values are handled in retargetMethodExpressions. if (propertyDescriptor.getValue("method-signature") == null || propertyDescriptor.getValue("type") != null) { if (attributesWithDeclaredDefaultValues == null) { BeanDescriptor beanDescriptor = componentMetadata.getBeanDescriptor(); attributesWithDeclaredDefaultValues = (Collection<String>) beanDescriptor.getValue(ATTRS_WITH_DECLARED_DEFAULT_VALUES); if (attributesWithDeclaredDefaultValues == null) { attributesWithDeclaredDefaultValues = new HashSet<>(); beanDescriptor.setValue(ATTRS_WITH_DECLARED_DEFAULT_VALUES, attributesWithDeclaredDefaultValues); } } attributesWithDeclaredDefaultValues.add(key); // Only store the attribute if it is literal text. If it // is a ValueExpression, it will be handled explicitly in // CompositeComponentAttributesELResolver.ExpressionEvalMap.get(). // If it is a MethodExpression, it will be dealt with in // retargetMethodExpressions. if (isLiteralText) { try { if (propertyDescriptors == null) { propertyDescriptors = getBeanInfo(component.getClass()).getPropertyDescriptors(); } } catch (IntrospectionException e) { throw new FacesException(e); } defaultValue = convertValueToTypeIfNecessary(key, defaultValue, propertyDescriptors, expressionFactory); attrs.put(key, defaultValue); } } } } } /** * Helper method to convert a value to a type as defined in PropertyDescriptor(s) * * @param name * @param value * @param propertyDescriptors * @return value */ private Object convertValueToTypeIfNecessary(String name, Object value, PropertyDescriptor[] propertyDescriptors, ExpressionFactory expressionFactory) { for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(name)) { value = expressionFactory.coerceToType(value, propertyDescriptor.getPropertyType()); break; } } return value; } /** * <p> * To enable EL Coercion to use JSF Custom converters, this method will call * <code>PropertyEditorManager.registerEditor()</code>, passing the * <code>ConverterPropertyEditor</code> class for the <code>targetClass</code> if the target * class is not one of the standard by-type converter target classes. * * @param targetClass the target class for which a PropertyEditory may or may not be created */ private void addPropertyEditorIfNecessary(Class<?> targetClass) { if (!registerPropertyEditors) { return; } PropertyEditor editor = findEditor(targetClass); if (editor != null) { return; } String className = targetClass.getName(); // Don't add a PropertyEditor for the standard by-type converters. if (targetClass.isPrimitive()) { return; } for (String standardClass : STANDARD_BY_TYPE_CONVERTER_CLASSES) { if (standardClass.indexOf(className) != -1) { return; } } Class<?> editorClass = ConverterPropertyEditorFactory.getDefaultInstance().definePropertyEditorClassFor(targetClass); if (editorClass != null) { PropertyEditorManager.registerEditor(targetClass, editorClass); } else { if (LOGGER.isLoggable(WARNING)) { LOGGER.warning(MessageFormat.format("definePropertyEditorClassFor({0}) returned null.", targetClass.getName())); } } } private Converter createConverterBasedOnClass(Class<?> targetClass, Class<?> baseClass) { Converter returnVal = (Converter) newConverter(targetClass, converterTypeMap, baseClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } // Search for converters registered to interfaces implemented by // targetClass Class<?>[] interfaces = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { returnVal = createConverterBasedOnClass(interfaces[i], null); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } } } // Search for converters registered to superclasses of targetClass Class<?> superclass = targetClass.getSuperclass(); if (superclass != null) { returnVal = createConverterBasedOnClass(superclass, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } } return returnVal; } /** * <p> * The same as newThing except that a single argument constructor that accepts a Class is looked * for before calling the no-arg version. * </p> * * <p> * PRECONDITIONS: the values in the Map are either Strings representing fully qualified java * class names, or java.lang.Class instances. * </p> * <p> * ALGORITHM: Look in the argument map for a value for the argument key. If found, if the value * is instanceof String, assume the String specifies a fully qualified java class name and * obtain the java.lang.Class instance for that String using Util.loadClass(). Replace the * String instance in the argument map with the Class instance. If the value is instanceof * Class, proceed. Assert that the value is either instanceof java.lang.Class or * java.lang.String. * </p> * <p> * Now that you have a java.lang.class, call its newInstance and return it as the result of this * method. * </p> * * @param key Used to look up the value in the <code>Map</code>. * @param map The <code>Map</code> that will be searched. * @param targetClass the target class for the single argument ctor * @return The new object instance. */ protected Object newConverter(Class<?> key, Map<Class<?>, Object> map, Class<?> targetClass) { assert key != null && map != null; Object result = null; Class<?> clazz; Object value; value = map.get(key); if (value == null) { return null; } assert value instanceof String || value instanceof Class; if (value instanceof String) { String cValue = (String) value; try { clazz = Util.loadClass(cValue, value); if (!associate.isDevModeEnabled()) { map.put(key, clazz); } assert clazz != null; } catch (Exception e) { throw new FacesException(e.getMessage(), e); } } else { clazz = (Class) value; } Constructor ctor = ReflectionUtils.lookupConstructor(clazz, Class.class); Throwable cause = null; if (ctor != null) { try { result = ctor.newInstance(targetClass); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { cause = e; } } else { try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { cause = e; } } if (null != cause) { throw new FacesException(MessageUtils.getExceptionMessageString(MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, clazz.getName()), cause); } return result; } /** * Get the bean manager. * * @return the bean manager. */ private BeanManager getBeanManager() { if (beanManager == null) { FacesContext facesContext = FacesContext.getCurrentInstance(); beanManager = Util.getCdiBeanManager(facesContext); } return beanManager; } private Behavior createCDIBehavior(String behaviorId) { if (version.isJsf23()) { return CdiUtils.createBehavior(getBeanManager(), behaviorId); } return null; } private Converter<?> createCDIConverter(String converterId) { if (version.isJsf23()) { return CdiUtils.createConverter(getBeanManager(), converterId); } return null; } private Validator<?> createCDIValidator(String validatorId) { if (version.isJsf23()) { return CdiUtils.createValidator(getBeanManager(), validatorId); } return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_256_0
crossvul-java_data_bad_54_0
/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import java.io.IOException; import javax.annotation.Nullable; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okio.Buffer; import okio.BufferedSink; final class RequestBuilder { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final String PATH_SEGMENT_ALWAYS_ENCODE_SET = " \"<>^`{}|\\?#"; private final String method; private final HttpUrl baseUrl; private @Nullable String relativeUrl; private @Nullable HttpUrl.Builder urlBuilder; private final Request.Builder requestBuilder; private @Nullable MediaType contentType; private final boolean hasBody; private @Nullable MultipartBody.Builder multipartBuilder; private @Nullable FormBody.Builder formBuilder; private @Nullable RequestBody body; RequestBuilder(String method, HttpUrl baseUrl, @Nullable String relativeUrl, @Nullable Headers headers, @Nullable MediaType contentType, boolean hasBody, boolean isFormEncoded, boolean isMultipart) { this.method = method; this.baseUrl = baseUrl; this.relativeUrl = relativeUrl; this.requestBuilder = new Request.Builder(); this.contentType = contentType; this.hasBody = hasBody; if (headers != null) { requestBuilder.headers(headers); } if (isFormEncoded) { // Will be set to 'body' in 'build'. formBuilder = new FormBody.Builder(); } else if (isMultipart) { // Will be set to 'body' in 'build'. multipartBuilder = new MultipartBody.Builder(); multipartBuilder.setType(MultipartBody.FORM); } } void setRelativeUrl(Object relativeUrl) { this.relativeUrl = relativeUrl.toString(); } void addHeader(String name, String value) { if ("Content-Type".equalsIgnoreCase(name)) { try { contentType = MediaType.get(value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Malformed content type: " + value, e); } } else { requestBuilder.addHeader(name, value); } } void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { // The relative URL is cleared when the first query parameter is set. throw new AssertionError(); } relativeUrl = relativeUrl.replace("{" + name + "}", canonicalizeForPath(value, encoded)); } private static String canonicalizeForPath(String input, boolean alreadyEncoded) { int codePoint; for (int i = 0, limit = input.length(); i < limit; i += Character.charCount(codePoint)) { codePoint = input.codePointAt(i); if (codePoint < 0x20 || codePoint >= 0x7f || PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1 || (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) { // Slow path: the character at i requires encoding! Buffer out = new Buffer(); out.writeUtf8(input, 0, i); canonicalizeForPath(out, input, i, limit, alreadyEncoded); return out.readUtf8(); } } // Fast path: no characters required encoding. return input; } private static void canonicalizeForPath(Buffer out, String input, int pos, int limit, boolean alreadyEncoded) { Buffer utf8Buffer = null; // Lazily allocated. int codePoint; for (int i = pos; i < limit; i += Character.charCount(codePoint)) { codePoint = input.codePointAt(i); if (alreadyEncoded && (codePoint == '\t' || codePoint == '\n' || codePoint == '\f' || codePoint == '\r')) { // Skip this character. } else if (codePoint < 0x20 || codePoint >= 0x7f || PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1 || (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) { // Percent encode this character. if (utf8Buffer == null) { utf8Buffer = new Buffer(); } utf8Buffer.writeUtf8CodePoint(codePoint); while (!utf8Buffer.exhausted()) { int b = utf8Buffer.readByte() & 0xff; out.writeByte('%'); out.writeByte(HEX_DIGITS[(b >> 4) & 0xf]); out.writeByte(HEX_DIGITS[b & 0xf]); } } else { // This character doesn't need encoding. Just copy it over. out.writeUtf8CodePoint(codePoint); } } } void addQueryParam(String name, @Nullable String value, boolean encoded) { if (relativeUrl != null) { // Do a one-time combination of the built relative URL and the base URL. urlBuilder = baseUrl.newBuilder(relativeUrl); if (urlBuilder == null) { throw new IllegalArgumentException( "Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl); } relativeUrl = null; } if (encoded) { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addEncodedQueryParameter(name, value); } else { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addQueryParameter(name, value); } } @SuppressWarnings("ConstantConditions") // Only called when isFormEncoded was true. void addFormField(String name, String value, boolean encoded) { if (encoded) { formBuilder.addEncoded(name, value); } else { formBuilder.add(name, value); } } @SuppressWarnings("ConstantConditions") // Only called when isMultipart was true. void addPart(Headers headers, RequestBody body) { multipartBuilder.addPart(headers, body); } @SuppressWarnings("ConstantConditions") // Only called when isMultipart was true. void addPart(MultipartBody.Part part) { multipartBuilder.addPart(part); } void setBody(RequestBody body) { this.body = body; } Request.Builder get() { HttpUrl url; HttpUrl.Builder urlBuilder = this.urlBuilder; if (urlBuilder != null) { url = urlBuilder.build(); } else { // No query parameters triggered builder creation, just combine the relative URL and base URL. //noinspection ConstantConditions Non-null if urlBuilder is null. url = baseUrl.resolve(relativeUrl); if (url == null) { throw new IllegalArgumentException( "Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl); } } RequestBody body = this.body; if (body == null) { // Try to pull from one of the builders. if (formBuilder != null) { body = formBuilder.build(); } else if (multipartBuilder != null) { body = multipartBuilder.build(); } else if (hasBody) { // Body is absent, make an empty body. body = RequestBody.create(null, new byte[0]); } } MediaType contentType = this.contentType; if (contentType != null) { if (body != null) { body = new ContentTypeOverridingRequestBody(body, contentType); } else { requestBuilder.addHeader("Content-Type", contentType.toString()); } } return requestBuilder .url(url) .method(method, body); } private static class ContentTypeOverridingRequestBody extends RequestBody { private final RequestBody delegate; private final MediaType contentType; ContentTypeOverridingRequestBody(RequestBody delegate, MediaType contentType) { this.delegate = delegate; this.contentType = contentType; } @Override public MediaType contentType() { return contentType; } @Override public long contentLength() throws IOException { return delegate.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { delegate.writeTo(sink); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_54_0
crossvul-java_data_bad_4612_1
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby; import com.google.common.base.CaseFormat; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.primitives.Primitives; import com.google.inject.Key; import com.google.inject.TypeLiteral; import static java.util.Objects.requireNonNull; import org.jooby.funzy.Throwing; import org.jooby.handlers.AssetHandler; import org.jooby.internal.RouteImpl; import org.jooby.internal.RouteMatcher; import org.jooby.internal.RoutePattern; import org.jooby.internal.RouteSourceImpl; import org.jooby.internal.SourceProvider; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; /** * Routes are a key concept in Jooby. Routes are executed in the same order they are defined. * * <h1>handlers</h1> * <p> * There are few type of handlers: {@link Route.Handler}, {@link Route.OneArgHandler} * {@link Route.ZeroArgHandler} and {@link Route.Filter}. They behave very similar, except that a * {@link Route.Filter} can decide if the next route handler can be executed or not. For example: * </p> * * <pre> * get("/filter", (req, rsp, chain) {@literal ->} { * if (someCondition) { * chain.next(req, rsp); * } else { * // respond, throw err, etc... * } * }); * </pre> * * While a {@link Route.Handler} always execute the next handler: * * <pre> * get("/path", (req, rsp) {@literal ->} { * rsp.send("handler"); * }); * * // filter version * get("/path", (req, rsp, chain) {@literal ->} { * rsp.send("handler"); * chain.next(req, rsp); * }); * </pre> * * The {@link Route.OneArgHandler} and {@link Route.ZeroArgHandler} offers a functional version of * generating a response: * * <pre>{@code * { * get("/path", req -> "handler"); * * get("/path", () -> "handler"); * } * }</pre> * * There is no need to call {@link Response#send(Object)}. * * <h1>path patterns</h1> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.jsp} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the * {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h2>variables</h2> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * <h1>routes semantic</h1> * <p> * Routes are executed in the order they are defined, for example: * </p> * * <pre> * get("/", (req, rsp) {@literal ->} { * log.info("first"); // start here and go to second * }); * * get("/", (req, rsp) {@literal ->} { * log.info("second"); // execute after first and go to final * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Please note first and second routes are converted to a filter, so previous example is the same * as: * * <pre> * get("/", (req, rsp, chain) {@literal ->} { * log.info("first"); // start here and go to second * chain.next(req, rsp); * }); * * get("/", (req, rsp, chain) {@literal ->} { * log.info("second"); // execute after first and go to final * chain.next(req, rsp); * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * <h2>script route</h2> * <p> * A script route can be defined using Lambda expressions, like: * </p> * * <pre> * get("/", (request, response) {@literal ->} { * response.send("Hello Jooby"); * }); * </pre> * * Due to the use of lambdas a route is a singleton and you should NOT use global variables. * For example this is a bad practice: * * <pre> * List{@literal <}String{@literal >} names = new ArrayList{@literal <>}(); // names produces side effects * get("/", (req, rsp) {@literal ->} { * names.add(req.param("name").value(); * // response will be different between calls. * rsp.send(names); * }); * </pre> * * <h2>mvc Route</h2> * <p> * A Mvc Route use annotations to define routes: * </p> * * <pre> * { * use(MyRoute.class); * } * </pre> * * MyRoute.java: * <pre> * {@literal @}Path("/") * public class MyRoute { * * {@literal @}GET * public String hello() { * return "Hello Jooby"; * } * } * </pre> * <p> * Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or * simplifications. * </p> * * <p> * To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path}, * {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes}. * </p> * * @author edgar * @since 0.1.0 */ public interface Route { /** * Provides useful information about where the route was defined. * * See {@link Definition#source()} and {@link Route#source()}. * * @author edgar * @since 1.0.0.CR4 */ interface Source { /** * There is no source information. */ Source BUILTIN = new Source() { @Override public int line() { return -1; } @Override public Optional<String> declaringClass() { return Optional.empty(); } @Override public String toString() { return "~builtin"; } }; /** * @return Line number where the route was defined or <code>-1</code> when not available. */ int line(); /** * @return Class where the route */ @Nonnull Optional<String> declaringClass(); } /** * Converts a route output to something else, see {@link Router#map(Mapper)}. * * <pre>{@code * { * // we got bar.. not foo * get("/foo", () -> "foo") * .map(value -> "bar"); * * // we got foo.. not bar * get("/bar", () -> "bar") * .map(value -> "foo"); * } * }</pre> * * If you want to apply a single map to several routes: * * <pre>{@code * { * with(() -> { * get("/foo", () -> "foo"); * * get("/bar", () -> "bar"); * * }).map(v -> "foo or bar"); * } * }</pre> * * You can apply a {@link Mapper} to specific return type: * * <pre>{@code * { * with(() -> { * get("/str", () -> "str"); * * get("/int", () -> 1); * * }).map(String v -> "{" + v + "}"); * } * }</pre> * * A call to <code>/str</code> produces <code>{str}</code>, while <code>/int</code> just * <code>1</code>. * * <strong>NOTE</strong>: You can apply the map operator to routes that produces an output. * * For example, the map operator will be silently ignored here: * * <pre>{@code * { * get("/", (req, rsp) -> { * rsp.send(...); * }).map(v -> ..); * } * }</pre> * * @author edgar * @param <T> Type to map. */ interface Mapper<T> { /** * Produces a new mapper by combining the two mapper into one. * * @param it The first mapper to apply. * @param next The second mapper to apply. * @return A new mapper. */ @SuppressWarnings({"rawtypes", "unchecked"}) @Nonnull static Mapper<Object> chain(final Mapper it, final Mapper next) { return create(it.name() + ">" + next.name(), v -> next.map(it.map(v))); } /** * Creates a new named mapper (just syntax suggar for creating a new mapper). * * @param name Mapper's name. * @param fn Map function. * @param <T> Value type. * @return A new mapper. */ @Nonnull static <T> Mapper<T> create(final String name, final Throwing.Function<T, Object> fn) { return new Route.Mapper<T>() { @Override public String name() { return name; } @Override public Object map(final T value) throws Throwable { return fn.apply(value); } @Override public String toString() { return name(); } }; } /** * @return Mapper's name. */ @Nonnull default String name() { String name = Optional.ofNullable(Strings.emptyToNull(getClass().getSimpleName())) .orElseGet(() -> { String classname = getClass().getName(); return classname.substring(classname.lastIndexOf('.') + 1); }); return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name); } /** * Map the type to something else. * * @param value Value to map. * @return Mapped value. * @throws Throwable If mapping fails. */ @Nonnull Object map(T value) throws Throwable; } /** * Common route properties, like static and global metadata via attributes, path exclusion, * produces and consumes types. * * @author edgar * @since 1.0.0.CR * @param <T> Attribute subtype. */ interface Props<T extends Props<T>> { /** * Set route attribute. Only primitives, string, class, enum or array of previous types are * allowed as attributes values. * * @param name Attribute's name. * @param value Attribute's value. * @return This instance. */ @Nonnull T attr(String name, Object value); /** * Tell jooby what renderer should use to render the output. * * @param name A renderer's name. * @return This instance. */ @Nonnull T renderer(final String name); /** * Explicit renderer to use or <code>null</code>. * * @return Explicit renderer to use or <code>null</code>. */ @Nullable String renderer(); /** * Set the route name. Route's name, helpful for debugging but also to implement dynamic and * advanced routing. See {@link Route.Chain#next(String, Request, Response)} * * * @param name A route's name. * @return This instance. */ @Nonnull T name(final String name); /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull default T consumes(final MediaType... consumes) { return consumes(Arrays.asList(consumes)); } /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull default T consumes(final String... consumes) { return consumes(MediaType.valueOf(consumes)); } /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull T consumes(final List<MediaType> consumes); /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull default T produces(final MediaType... produces) { return produces(Arrays.asList(produces)); } /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull default T produces(final String... produces) { return produces(MediaType.valueOf(produces)); } /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull T produces(final List<MediaType> produces); /** * Excludes one or more path pattern from this route, useful for filter: * * <pre> * { * use("*", req {@literal ->} { * ... * }).excludes("/logout"); * } * </pre> * * @param excludes A path pattern. * @return This instance. */ @Nonnull default T excludes(final String... excludes) { return excludes(Arrays.asList(excludes)); } /** * Excludes one or more path pattern from this route, useful for filter: * * <pre> * { * use("*", req {@literal ->} { * ... * }).excludes("/logout"); * } * </pre> * * @param excludes A path pattern. * @return This instance. */ @Nonnull T excludes(final List<String> excludes); @Nonnull T map(Mapper<?> mapper); } /** * Collection of {@link Route.Props} useful for registering/setting route options at once. * * See {@link Router#get(String, String, String, OneArgHandler)} and variants. * * @author edgar * @since 0.5.0 */ @SuppressWarnings({"unchecked", "rawtypes"}) class Collection implements Props<Collection> { /** List of definitions. */ private final Route.Props[] routes; /** * Creates a new collection of route definitions. * * @param definitions Collection of route definitions. */ public Collection(final Route.Props... definitions) { this.routes = requireNonNull(definitions, "Route definitions are required."); } @Override public Collection name(final String name) { for (Props definition : routes) { definition.name(name); } return this; } @Override public String renderer() { return routes[0].renderer(); } @Override public Collection renderer(final String name) { for (Props definition : routes) { definition.renderer(name); } return this; } @Override public Collection consumes(final List<MediaType> types) { for (Props definition : routes) { definition.consumes(types); } return this; } @Override public Collection produces(final List<MediaType> types) { for (Props definition : routes) { definition.produces(types); } return this; } @Override public Collection attr(final String name, final Object value) { for (Props definition : routes) { definition.attr(name, value); } return this; } @Override public Collection excludes(final List<String> excludes) { for (Props definition : routes) { definition.excludes(excludes); } return this; } @Override public Collection map(final Mapper<?> mapper) { for (Props route : routes) { route.map(mapper); } return this; } } /** * DSL for customize routes. * * <p> * Some examples: * </p> * * <pre> * public class MyApp extends Jooby { * { * get("/", () {@literal ->} "GET"); * * post("/", req {@literal ->} "POST"); * * put("/", (req, rsp) {@literal ->} rsp.send("PUT")); * } * } * </pre> * * <h1>Setting what a route can consumes</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .consumes(MediaType.json); * } * } * </pre> * * <h1>Setting what a route can produces</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .produces(MediaType.json); * } * } * </pre> * * <h1>Adding a name</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .name("My Root"); * } * } * </pre> * * @author edgar * @since 0.1.0 */ class Definition implements Props<Definition> { /** * Route's name. */ private String name = "/anonymous"; /** * A route pattern. */ private RoutePattern cpattern; /** * The target route. */ private Filter filter; /** * Defines the media types that the methods of a resource class or can accept. Default is: * {@code *}/{@code *}. */ private List<MediaType> consumes = MediaType.ALL; /** * Defines the media types that the methods of a resource class or can produces. Default is: * {@code *}/{@code *}. */ private List<MediaType> produces = MediaType.ALL; /** * A HTTP verb or <code>*</code>. */ private String method; /** * A path pattern. */ private String pattern; private List<RoutePattern> excludes = Collections.emptyList(); private Map<String, Object> attributes = ImmutableMap.of(); private Mapper<?> mapper; private int line; private String declaringClass; String prefix; private String renderer; /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.Handler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. * @param caseSensitiveRouting Configure case for routing algorithm. */ public Definition(final String verb, final String pattern, final Route.Handler handler, boolean caseSensitiveRouting) { this(verb, pattern, (Route.Filter) handler, caseSensitiveRouting); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.OneArgHandler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.ZeroArgHandler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param filter A callback to execute. */ public Definition(final String method, final String pattern, final Filter filter) { this(method, pattern, filter, true); } /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param filter A callback to execute. * @param caseSensitiveRouting Configure case for routing algorithm. */ public Definition(final String method, final String pattern, final Filter filter, boolean caseSensitiveRouting) { requireNonNull(pattern, "A route path is required."); requireNonNull(filter, "A filter is required."); this.method = method.toUpperCase(); this.cpattern = new RoutePattern(method, pattern, !caseSensitiveRouting); // normalized pattern this.pattern = cpattern.pattern(); this.filter = filter; SourceProvider.INSTANCE.get().ifPresent(source -> { this.line = source.getLineNumber(); this.declaringClass = source.getClassName(); }); } /** * <h1>Path Patterns</h1> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.jsp} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath * the {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h2>Variables</h2> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * @return A path pattern. */ @Nonnull public String pattern() { return pattern; } @Nullable public String renderer() { return renderer; } @Override public Definition renderer(final String name) { this.renderer = name; return this; } /** * @return List of path variables (if any). */ @Nonnull public List<String> vars() { return cpattern.vars(); } /** * Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. * * @return Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. */ @Nonnull public boolean glob() { return cpattern.glob(); } /** * Source information (where the route was defined). * * @return Source information (where the route was defined). */ @Nonnull public Route.Source source() { return new RouteSourceImpl(declaringClass, line); } /** * Recreate a route path and apply the given variables. * * @param vars Path variables. * @return A route pattern. */ @Nonnull public String reverse(final Map<String, Object> vars) { return cpattern.reverse(vars); } /** * Recreate a route path and apply the given variables. * * @param values Path variable values. * @return A route pattern. */ @Nonnull public String reverse(final Object... values) { return cpattern.reverse(values); } @Override @Nonnull public Definition attr(final String name, final Object value) { requireNonNull(name, "Attribute name is required."); requireNonNull(value, "Attribute value is required."); if (valid(value)) { attributes = ImmutableMap.<String, Object>builder() .putAll(attributes) .put(name, value) .build(); } return this; } private boolean valid(final Object value) { if (Primitives.isWrapperType(Primitives.wrap(value.getClass()))) { return true; } if (value instanceof String || value instanceof Enum || value instanceof Class) { return true; } if (value.getClass().isArray() && Array.getLength(value) > 0) { return valid(Array.get(value, 0)); } if (value instanceof Map && ((Map) value).size() > 0) { Map.Entry e = (Map.Entry) ((Map) value).entrySet().iterator().next(); return valid(e.getKey()) && valid(e.getValue()); } return false; } /** * Get an attribute by name. * * @param name Attribute's name. * @param <T> Attribute's type. * @return Attribute's value or <code>null</code>. */ @SuppressWarnings("unchecked") @Nonnull public <T> T attr(final String name) { return (T) attributes.get(name); } /** * @return A read only view of attributes. */ @Nonnull public Map<String, Object> attributes() { return attributes; } /** * Test if the route matches the given verb, path, content type and accept header. * * @param method A HTTP verb. * @param path Current HTTP path. * @param contentType The <code>Content-Type</code> header. * @param accept The <code>Accept</code> header. * @return A route or an empty optional. */ @Nonnull public Optional<Route> matches(final String method, final String path, final MediaType contentType, final List<MediaType> accept) { String fpath = method + path; if (excludes.size() > 0 && excludes(fpath)) { return Optional.empty(); } RouteMatcher matcher = cpattern.matcher(fpath); if (matcher.matches()) { List<MediaType> result = MediaType.matcher(accept).filter(this.produces); if (result.size() > 0 && canConsume(contentType)) { // keep accept when */* List<MediaType> produces = result.size() == 1 && result.get(0).name().equals("*/*") ? accept : this.produces; return Optional .of(asRoute(method, matcher, produces, new RouteSourceImpl(declaringClass, line))); } } return Optional.empty(); } /** * @return HTTP method or <code>*</code>. */ @Nonnull public String method() { return method; } /** * @return Handler behind this route. */ @Nonnull public Route.Filter filter() { return filter; } /** * Route's name, helpful for debugging but also to implement dynamic and advanced routing. See * {@link Route.Chain#next(String, Request, Response)} * * @return Route name. Default is: <code>anonymous</code>. */ @Nonnull public String name() { return name; } /** * Set the route name. Route's name, helpful for debugging but also to implement dynamic and * advanced routing. See {@link Route.Chain#next(String, Request, Response)} * * * @param name A route's name. * @return This definition. */ @Override @Nonnull public Definition name(final String name) { checkArgument(!Strings.isNullOrEmpty(name), "A route's name is required."); this.name = normalize(prefix != null ? prefix + "/" + name : name); return this; } /** * Test if the route definition can consume a media type. * * @param type A media type to test. * @return True, if the route can consume the given media type. */ public boolean canConsume(final MediaType type) { return MediaType.matcher(Arrays.asList(type)).matches(consumes); } /** * Test if the route definition can consume a media type. * * @param type A media type to test. * @return True, if the route can consume the given media type. */ public boolean canConsume(final String type) { return MediaType.matcher(MediaType.valueOf(type)).matches(consumes); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final List<MediaType> types) { return MediaType.matcher(types).matches(produces); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final MediaType... types) { return canProduce(Arrays.asList(types)); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final String... types) { return canProduce(MediaType.valueOf(types)); } @Override public Definition consumes(final List<MediaType> types) { checkArgument(types != null && types.size() > 0, "Consumes types are required"); if (types.size() > 1) { this.consumes = Lists.newLinkedList(types); Collections.sort(this.consumes); } else { this.consumes = ImmutableList.of(types.get(0)); } return this; } @Override public Definition produces(final List<MediaType> types) { checkArgument(types != null && types.size() > 0, "Produces types are required"); if (types.size() > 1) { this.produces = Lists.newLinkedList(types); Collections.sort(this.produces); } else { this.produces = ImmutableList.of(types.get(0)); } return this; } @Override public Definition excludes(final List<String> excludes) { this.excludes = excludes.stream() .map(it -> new RoutePattern(method, it)) .collect(Collectors.toList()); return this; } /** * @return List of exclusion filters (if any). */ @Nonnull public List<String> excludes() { return excludes.stream().map(r -> r.pattern()).collect(Collectors.toList()); } private boolean excludes(final String path) { for (RoutePattern pattern : excludes) { if (pattern.matcher(path).matches()) { return true; } } return false; } /** * @return All the types this route can consumes. */ @Nonnull public List<MediaType> consumes() { return Collections.unmodifiableList(this.consumes); } /** * @return All the types this route can produces. */ @Nonnull public List<MediaType> produces() { return Collections.unmodifiableList(this.produces); } @Override @Nonnull public Definition map(final Mapper<?> mapper) { this.mapper = requireNonNull(mapper, "Mapper is required."); return this; } /** * Set the line where this route is defined. * * @param line Line number. * @return This instance. */ @Nonnull public Definition line(final int line) { this.line = line; return this; } /** * Set the class where this route is defined. * * @param declaringClass A source class. * @return This instance. */ @Nonnull public Definition declaringClass(final String declaringClass) { this.declaringClass = declaringClass; return this; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(method()).append(" ").append(pattern()).append("\n"); buffer.append(" name: ").append(name()).append("\n"); buffer.append(" excludes: ").append(excludes).append("\n"); buffer.append(" consumes: ").append(consumes()).append("\n"); buffer.append(" produces: ").append(produces()).append("\n"); return buffer.toString(); } /** * Creates a new route. * * @param method A HTTP verb. * @param matcher A route matcher. * @param produces List of produces types. * @param source Route source. * @return A new route. */ private Route asRoute(final String method, final RouteMatcher matcher, final List<MediaType> produces, final Route.Source source) { return new RouteImpl(filter, this, method, matcher.path(), produces, matcher.vars(), mapper, source); } } /** * A forwarding route. * * @author edgar * @since 0.1.0 */ class Forwarding implements Route { /** * Target route. */ private final Route route; /** * Creates a new {@link Forwarding} route. * * @param route A target route. */ public Forwarding(final Route route) { this.route = route; } @Override public String renderer() { return route.renderer(); } @Override public String path() { return route.path(); } @Override public String method() { return route.method(); } @Override public String pattern() { return route.pattern(); } @Override public String name() { return route.name(); } @Override public Map<Object, String> vars() { return route.vars(); } @Override public List<MediaType> consumes() { return route.consumes(); } @Override public List<MediaType> produces() { return route.produces(); } @Override public Map<String, Object> attributes() { return route.attributes(); } @Override public <T> T attr(final String name) { return route.attr(name); } @Override public boolean glob() { return route.glob(); } @Override public String reverse(final Map<String, Object> vars) { return route.reverse(vars); } @Override public String reverse(final Object... values) { return route.reverse(values); } @Override public Source source() { return route.source(); } @Override public String print() { return route.print(); } @Override public String print(final int indent) { return route.print(indent); } @Override public String toString() { return route.toString(); } /** * Find a target route. * * @param route A route to check. * @return A target route. */ public static Route unwrap(final Route route) { Route root = route; while (root instanceof Forwarding) { root = ((Forwarding) root).route; } return root; } } /** * The most advanced route handler which let you decided if the next route handler in the chain * can be executed or not. Example of filters are: * * <p> * Auth handler example: * </p> * * <pre> * String token = req.header("token").value(); * if (token != null) { * // validate token... * if (valid(token)) { * chain.next(req, rsp); * } * } else { * rsp.status(403); * } * </pre> * * <p> * Logging/Around handler example: * </p> * * <pre> * long start = System.currentTimeMillis(); * chain.next(req, rsp); * long end = System.currentTimeMillis(); * log.info("Request: {} took {}ms", req.path(), end - start); * </pre> * * NOTE: Don't forget to call {@link Route.Chain#next(Request, Response)} if next route handler * need to be executed. * * @author edgar * @since 0.1.0 */ public interface Filter { /** * The <code>handle</code> method of the Filter is called by the server each time a * request/response pair is passed through the chain due to a client request for a resource at * the end of the chain. * The {@link Route.Chain} passed in to this method allows the Filter to pass on the request and * response to the next entity in the chain. * * <p> * A typical implementation of this method would follow the following pattern: * </p> * <ul> * <li>Examine the request</li> * <li>Optionally wrap the request object with a custom implementation to filter content or * headers for input filtering</li> * <li>Optionally wrap the response object with a custom implementation to filter content or * headers for output filtering</li> * <li> * <ul> * <li><strong>Either</strong> invoke the next entity in the chain using the {@link Route.Chain} * object (<code>chain.next(req, rsp)</code>),</li> * <li><strong>or</strong> not pass on the request/response pair to the next entity in the * filter chain to block the request processing</li> * </ul> * <li>Directly set headers on the response after invocation of the next entity in the filter * chain.</li> * </ul> * * @param req A HTTP request. * @param rsp A HTTP response. * @param chain A route chain. * @throws Throwable If something goes wrong. */ void handle(Request req, Response rsp, Route.Chain chain) throws Throwable; } /** * Allow to customize an asset handler. * * @author edgar */ class AssetDefinition extends Definition { private Boolean etag; private String cdn; private Object maxAge; private Boolean lastModifiedSince; private Integer statusCode; /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A callback to execute. * @param caseSensitiveRouting Configure case for routing algorithm. */ public AssetDefinition(final String method, final String pattern, final Route.Filter handler, boolean caseSensitiveRouting) { super(method, pattern, handler, caseSensitiveRouting); } @Nonnull @Override public AssetHandler filter() { return (AssetHandler) super.filter(); } /** * Indicates what to do when an asset is missing (not resolved). Default action is to resolve them * as <code>404 (NOT FOUND)</code> request. * * If you specify a status code &lt;= 0, missing assets are ignored and the next handler on pipeline * will be executed. * * @param statusCode HTTP code or 0. * @return This route definition. */ public AssetDefinition onMissing(final int statusCode) { if (this.statusCode == null) { filter().onMissing(statusCode); this.statusCode = statusCode; } return this; } /** * @param etag Turn on/off etag support. * @return This route definition. */ public AssetDefinition etag(final boolean etag) { if (this.etag == null) { filter().etag(etag); this.etag = etag; } return this; } /** * @param enabled Turn on/off last modified support. * @return This route definition. */ public AssetDefinition lastModified(final boolean enabled) { if (this.lastModifiedSince == null) { filter().lastModified(enabled); this.lastModifiedSince = enabled; } return this; } /** * @param cdn If set, every resolved asset will be serve from it. * @return This route definition. */ public AssetDefinition cdn(final String cdn) { if (this.cdn == null) { filter().cdn(cdn); this.cdn = cdn; } return this; } /** * @param maxAge Set the cache header max-age value. * @return This route definition. */ public AssetDefinition maxAge(final Duration maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } /** * @param maxAge Set the cache header max-age value in seconds. * @return This route definition. */ public AssetDefinition maxAge(final long maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } /** * Parse value as {@link Duration}. If the value is already a number then it uses as seconds. * Otherwise, it parse expressions like: 8m, 1h, 365d, etc... * * @param maxAge Set the cache header max-age value in seconds. * @return This route definition. */ public AssetDefinition maxAge(final String maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } } /** * A route handler that always call {@link Chain#next(Request, Response)}. * * <pre> * public class MyApp extends Jooby { * { * get("/", (req, rsp) {@literal ->} rsp.send("Hello")); * } * } * </pre> * * @author edgar * @since 0.1.0 */ interface Handler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { handle(req, rsp); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ void handle(Request req, Response rsp) throws Throwable; } /** * A handler for a MVC route, it extends {@link Handler} by adding a reference to the method * and class behind this route. * * @author edgar * @since 0.6.2 */ interface MethodHandler extends Handler { /** * Target method. * * @return Target method. */ @Nonnull Method method(); /** * Target class. * * @return Target class. */ @Nonnull Class<?> implementingClass(); } /** * A functional route handler that use the return value as HTTP response. * * <pre> * { * get("/",(req {@literal ->} "Hello"); * } * </pre> * * @author edgar * @since 0.1.1 */ interface OneArgHandler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { Object result = handle(req); rsp.send(result); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @param req A HTTP request. * @return Message to send. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ Object handle(Request req) throws Throwable; } /** * A functional handler that use the return value as HTTP response. * * <pre> * public class MyApp extends Jooby { * { * get("/", () {@literal ->} "Hello"); * } * } * </pre> * * @author edgar * @since 0.1.1 */ interface ZeroArgHandler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { Object result = handle(); rsp.send(result); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @return Message to send. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ Object handle() throws Throwable; } /** * <h2>before</h2> * * Allows for customized handler execution chains. It will be invoked before the actual handler. * * <pre>{@code * { * before((req, rsp) -> { * // your code goes here * }); * } * }</pre> * * You are allowed to modify the request and response objects. * * Please note that the <code>before</code> handler is just syntax sugar for {@link Route.Filter}. * For example, the <code>before</code> handler was implemented as: * * <pre>{@code * { * use("*", "*", (req, rsp, chain) -> { * before(req, rsp); * // your code goes here * chain.next(req, rsp); * }); * } * }</pre> * * A <code>before</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * before((req, rsp) -> { * // your code goes here * }); * * get("/path", req -> { * // your code goes here * return ...; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * @author edgar * @since 1.0.0.CR */ interface Before extends Route.Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { handle(req, rsp); chain.next(req, rsp); } /** * Allows for customized handler execution chains. It will be invoked before the actual handler. * * @param req Request. * @param rsp Response * @throws Throwable If something goes wrong. */ void handle(Request req, Response rsp) throws Throwable; } /** * <h2>after</h2> * * Allows for customized response before send it. It will be invoked at the time a response need * to be send. * * <pre>{@code * { * after("GET", "*", (req, rsp, result) -> { * // your code goes here * return result; * }); * } * }</pre> * * You are allowed to modify the request, response and result objects. The handler returns a * {@link Result} which can be the same or an entirely new {@link Result}. * * Please note that the <code>after</code> handler is just syntax sugar for * {@link Route.Filter}. * For example, the <code>after</code> handler was implemented as: * * <pre>{@code * { * use("GET", "*", (req, rsp, chain) -> { * chain.next(req, new Response.Forwarding(rsp) { * public void send(Result result) { * rsp.send(after(req, rsp, result); * } * }); * }); * } * }</pre> * * Due <code>after</code> is implemented by wrapping the {@link Response} object. A * <code>after</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * after("GET", "/path", (req, rsp, result) -> { * // your code goes here * return result; * }); * * get("/path", req -> { * return "hello"; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * @author edgar * @since 1.0.0.CR */ interface After extends Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { rsp.after(this); chain.next(req, rsp); } /** * Allows for customized response before send it. It will be invoked at the time a response need * to be send. * * @param req Request. * @param rsp Response * @param result Result. * @return Same or new result. * @throws Exception If something goes wrong. */ Result handle(Request req, Response rsp, Result result) throws Exception; } /** * <h2>complete</h2> * * Allows for log and cleanup a request. It will be invoked after we send a response. * * <pre>{@code * { * complete((req, rsp, cause) -> { * // your code goes here * }); * } * }</pre> * * You are NOT allowed to modify the request and response objects. The <code>cause</code> is an * {@link Optional} with a {@link Throwable} useful to identify problems. * * The goal of the <code>complete</code> handler is to probably cleanup request object and log * responses. * * Please note that the <code>complete</code> handler is just syntax sugar for * {@link Route.Filter}. * For example, the <code>complete</code> handler was implemented as: * * <pre>{@code * { * use("*", "*", (req, rsp, chain) -> { * Optional<Throwable> err = Optional.empty(); * try { * chain.next(req, rsp); * } catch (Throwable cause) { * err = Optional.of(cause); * } finally { * complete(req, rsp, err); * } * }); * } * }</pre> * * An <code>complete</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * complete((req, rsp, cause) -> { * // your code goes here * }); * * get(req -> { * return "hello"; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * <h2>example</h2> * <p> * Suppose you have a transactional resource, like a database connection. The next example shows * you how to implement a simple and effective <code>transaction-per-request</code> pattern: * </p> * * <pre>{@code * { * // start transaction * before((req, rsp) -> { * DataSource ds = req.require(DataSource.class); * Connection connection = ds.getConnection(); * Transaction trx = connection.getTransaction(); * trx.begin(); * req.set("connection", connection); * return true; * }); * * // commit/rollback transaction * complete((req, rsp, cause) -> { * // unbind connection from request * try(Connection connection = req.unset("connection").get()) { * Transaction trx = connection.getTransaction(); * if (cause.ifPresent()) { * trx.rollback(); * } else { * trx.commit(); * } * } * }); * * // your transactional routes goes here * get("/api/something", req -> { * Connection connection = req.get("connection"); * // work with connection * }); * } * }</pre> * * @author edgar * @since 1.0.0.CR */ interface Complete extends Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { rsp.complete(this); chain.next(req, rsp); } /** * Allows for log and cleanup a request. It will be invoked after we send a response. * * @param req Request. * @param rsp Response * @param cause Empty optional on success. Otherwise, it contains the exception. */ void handle(Request req, Response rsp, Optional<Throwable> cause); } /** * Chain of routes to be executed. It invokes the next route in the chain. * * @author edgar * @since 0.1.0 */ interface Chain { /** * Invokes the next route in the chain where {@link Route#name()} starts with the given prefix. * * @param prefix Iterates over the route chain and keep routes that start with the given prefix. * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If invocation goes wrong. */ void next(@Nullable String prefix, Request req, Response rsp) throws Throwable; /** * Invokes the next route in the chain. * * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If invocation goes wrong. */ default void next(final Request req, final Response rsp) throws Throwable { next(null, req, rsp); } /** * All the pending/next routes from pipeline. Example: * * <pre>{@code * use("*", (req, rsp, chain) -> { * List<Route> routes = chain.routes(); * assertEquals(2, routes.size()); * assertEquals("/r2", routes.get(0).name()); * assertEquals("/r3", routes.get(1).name()); * assertEquals("/786/:id", routes.get(routes.size() - 1).pattern()); * * chain.next(req, rsp); * }).name("r1"); * * use("/786/**", (req, rsp, chain) -> { * List<Route> routes = chain.routes(); * assertEquals(1, routes.size()); * assertEquals("/r3", routes.get(0).name()); * assertEquals("/786/:id", routes.get(routes.size() - 1).pattern()); * chain.next(req, rsp); * }).name("r2"); * * get("/786/:id", req -> { * return req.param("id").value(); * }).name("r3"); * }</pre> * * @return Next routes in the pipeline or empty list. */ List<Route> routes(); } /** Route key. */ Key<Set<Route.Definition>> KEY = Key.get(new TypeLiteral<Set<Route.Definition>>() { }); char OUT_OF_PATH = '\u200B'; String GET = "GET"; String POST = "POST"; String PUT = "PUT"; String DELETE = "DELETE"; String PATCH = "PATCH"; String HEAD = "HEAD"; String CONNECT = "CONNECT"; String OPTIONS = "OPTIONS"; String TRACE = "TRACE"; /** * Well known HTTP methods. */ List<String> METHODS = ImmutableList.<String>builder() .add(GET, POST, PUT, DELETE, PATCH, HEAD, CONNECT, OPTIONS, TRACE) .build(); /** * @return Current request path. */ @Nonnull String path(); /** * @return Current HTTP method. */ @Nonnull String method(); /** * @return The currently matched pattern. */ @Nonnull String pattern(); /** * Route's name, helpful for debugging but also to implement dynamic and advanced routing. See * {@link Route.Chain#next(String, Request, Response)} * * @return Route name, defaults to <code>"anonymous"</code> */ @Nonnull String name(); /** * Path variables, either named or by index (capturing group). * * <pre> * /path/:var * </pre> * * Variable <code>var</code> is accessible by name: <code>var</code> or index: <code>0</code>. * * @return The currently matched path variables (if any). */ @Nonnull Map<Object, String> vars(); /** * @return List all the types this route can consumes, defaults is: {@code * / *}. */ @Nonnull List<MediaType> consumes(); /** * @return List all the types this route can produces, defaults is: {@code * / *}. */ @Nonnull List<MediaType> produces(); /** * True, when route's name starts with the given prefix. Useful for dynamic routing. See * {@link Route.Chain#next(String, Request, Response)} * * @param prefix Prefix to check for. * @return True, when route's name starts with the given prefix. */ default boolean apply(final String prefix) { return name().startsWith(prefix); } /** * @return All the available attributes in the execution chain. */ @Nonnull Map<String, Object> attributes(); /** * Attribute by name. * * @param name Attribute's name. * @param <T> Attribute's type. * @return Attribute value. */ @SuppressWarnings("unchecked") @Nonnull default <T> T attr(final String name) { return (T) attributes().get(name); } /** * Explicit renderer to use or <code>null</code>. * * @return Explicit renderer to use or <code>null</code>. */ @Nonnull String renderer(); /** * Indicates if the {@link #pattern()} contains a glob character, like <code>?</code>, * <code>*</code> or <code>**</code>. * * @return Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. */ boolean glob(); /** * Recreate a route path and apply the given variables. * * @param vars Path variables. * @return A route pattern. */ @Nonnull String reverse(final Map<String, Object> vars); /** * Recreate a route path and apply the given variables. * * @param values Path variable values. * @return A route pattern. */ @Nonnull String reverse(final Object... values); /** * Normalize a path by removing double or trailing slashes. * * @param path A path to normalize. * @return A normalized path. */ @Nonnull static String normalize(final String path) { return RoutePattern.normalize(path); } /** * Remove invalid path mark when present. * * @param path Path. * @return Original path. */ @Nonnull static String unerrpath(final String path) { if (path.charAt(0) == OUT_OF_PATH) { return path.substring(1); } return path; } /** * Mark a path as invalid. * * @param path Path. * @return Invalid path. */ @Nonnull static String errpath(final String path) { return OUT_OF_PATH + path; } /** * Source information (where the route was defined). * * @return Source information (where the route was defined). */ @Nonnull Route.Source source(); /** * Print route information like: method, path, source, etc... Useful for debugging. * * @param indent Indent level * @return Output. */ @Nonnull default String print(final int indent) { StringBuilder buff = new StringBuilder(); String[] header = {"Method", "Path", "Source", "Name", "Pattern", "Consumes", "Produces"}; String[] values = {method(), path(), source().toString(), name(), pattern(), consumes().toString(), produces().toString()}; BiConsumer<Function<Integer, String>, Character> format = (v, s) -> { buff.append(Strings.padEnd("", indent, ' ')) .append("|").append(s); for (int i = 0; i < header.length; i++) { buff .append(Strings.padEnd(v.apply(i), Math.max(header[i].length(), values[i].length()), s)) .append(s).append("|").append(s); } buff.setLength(buff.length() - 1); }; format.accept(i -> header[i], ' '); buff.append("\n"); format.accept(i -> "-", '-'); buff.append("\n"); format.accept(i -> values[i], ' '); return buff.toString(); } /** * Print route information like: method, path, source, etc... Useful for debugging. * * @return Output. */ @Nonnull default String print() { return print(0); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_1
crossvul-java_data_good_54_0
/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import java.io.IOException; import java.util.regex.Pattern; import javax.annotation.Nullable; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okio.Buffer; import okio.BufferedSink; final class RequestBuilder { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final String PATH_SEGMENT_ALWAYS_ENCODE_SET = " \"<>^`{}|\\?#"; /** * Matches strings that contain {@code .} or {@code ..} as a complete path segment. This also * matches dots in their percent-encoded form, {@code %2E}. * * <p>It is okay to have these strings within a larger path segment (like {@code a..z} or {@code * index.html}) but when alone they have a special meaning. A single dot resolves to no path * segment so {@code /one/./three/} becomes {@code /one/three/}. A double-dot pops the preceding * directory, so {@code /one/../three/} becomes {@code /three/}. * * <p>We forbid these in Retrofit paths because they're likely to have the unintended effect. * For example, passing {@code ..} to {@code DELETE /account/book/{isbn}/} yields {@code DELETE * /account/}. */ private static final Pattern PATH_TRAVERSAL = Pattern.compile("(.*/)?(\\.|%2e|%2E){1,2}(/.*)?"); private final String method; private final HttpUrl baseUrl; private @Nullable String relativeUrl; private @Nullable HttpUrl.Builder urlBuilder; private final Request.Builder requestBuilder; private @Nullable MediaType contentType; private final boolean hasBody; private @Nullable MultipartBody.Builder multipartBuilder; private @Nullable FormBody.Builder formBuilder; private @Nullable RequestBody body; RequestBuilder(String method, HttpUrl baseUrl, @Nullable String relativeUrl, @Nullable Headers headers, @Nullable MediaType contentType, boolean hasBody, boolean isFormEncoded, boolean isMultipart) { this.method = method; this.baseUrl = baseUrl; this.relativeUrl = relativeUrl; this.requestBuilder = new Request.Builder(); this.contentType = contentType; this.hasBody = hasBody; if (headers != null) { requestBuilder.headers(headers); } if (isFormEncoded) { // Will be set to 'body' in 'build'. formBuilder = new FormBody.Builder(); } else if (isMultipart) { // Will be set to 'body' in 'build'. multipartBuilder = new MultipartBody.Builder(); multipartBuilder.setType(MultipartBody.FORM); } } void setRelativeUrl(Object relativeUrl) { this.relativeUrl = relativeUrl.toString(); } void addHeader(String name, String value) { if ("Content-Type".equalsIgnoreCase(name)) { try { contentType = MediaType.get(value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Malformed content type: " + value, e); } } else { requestBuilder.addHeader(name, value); } } void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { // The relative URL is cleared when the first query parameter is set. throw new AssertionError(); } String replacement = canonicalizeForPath(value, encoded); String newRelativeUrl = relativeUrl.replace("{" + name + "}", replacement); if (PATH_TRAVERSAL.matcher(newRelativeUrl).matches()) { throw new IllegalArgumentException( "@Path parameters shouldn't perform path traversal ('.' or '..'): " + value); } relativeUrl = newRelativeUrl; } private static String canonicalizeForPath(String input, boolean alreadyEncoded) { int codePoint; for (int i = 0, limit = input.length(); i < limit; i += Character.charCount(codePoint)) { codePoint = input.codePointAt(i); if (codePoint < 0x20 || codePoint >= 0x7f || PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1 || (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) { // Slow path: the character at i requires encoding! Buffer out = new Buffer(); out.writeUtf8(input, 0, i); canonicalizeForPath(out, input, i, limit, alreadyEncoded); return out.readUtf8(); } } // Fast path: no characters required encoding. return input; } private static void canonicalizeForPath(Buffer out, String input, int pos, int limit, boolean alreadyEncoded) { Buffer utf8Buffer = null; // Lazily allocated. int codePoint; for (int i = pos; i < limit; i += Character.charCount(codePoint)) { codePoint = input.codePointAt(i); if (alreadyEncoded && (codePoint == '\t' || codePoint == '\n' || codePoint == '\f' || codePoint == '\r')) { // Skip this character. } else if (codePoint < 0x20 || codePoint >= 0x7f || PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1 || (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) { // Percent encode this character. if (utf8Buffer == null) { utf8Buffer = new Buffer(); } utf8Buffer.writeUtf8CodePoint(codePoint); while (!utf8Buffer.exhausted()) { int b = utf8Buffer.readByte() & 0xff; out.writeByte('%'); out.writeByte(HEX_DIGITS[(b >> 4) & 0xf]); out.writeByte(HEX_DIGITS[b & 0xf]); } } else { // This character doesn't need encoding. Just copy it over. out.writeUtf8CodePoint(codePoint); } } } void addQueryParam(String name, @Nullable String value, boolean encoded) { if (relativeUrl != null) { // Do a one-time combination of the built relative URL and the base URL. urlBuilder = baseUrl.newBuilder(relativeUrl); if (urlBuilder == null) { throw new IllegalArgumentException( "Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl); } relativeUrl = null; } if (encoded) { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addEncodedQueryParameter(name, value); } else { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addQueryParameter(name, value); } } @SuppressWarnings("ConstantConditions") // Only called when isFormEncoded was true. void addFormField(String name, String value, boolean encoded) { if (encoded) { formBuilder.addEncoded(name, value); } else { formBuilder.add(name, value); } } @SuppressWarnings("ConstantConditions") // Only called when isMultipart was true. void addPart(Headers headers, RequestBody body) { multipartBuilder.addPart(headers, body); } @SuppressWarnings("ConstantConditions") // Only called when isMultipart was true. void addPart(MultipartBody.Part part) { multipartBuilder.addPart(part); } void setBody(RequestBody body) { this.body = body; } Request.Builder get() { HttpUrl url; HttpUrl.Builder urlBuilder = this.urlBuilder; if (urlBuilder != null) { url = urlBuilder.build(); } else { // No query parameters triggered builder creation, just combine the relative URL and base URL. //noinspection ConstantConditions Non-null if urlBuilder is null. url = baseUrl.resolve(relativeUrl); if (url == null) { throw new IllegalArgumentException( "Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl); } } RequestBody body = this.body; if (body == null) { // Try to pull from one of the builders. if (formBuilder != null) { body = formBuilder.build(); } else if (multipartBuilder != null) { body = multipartBuilder.build(); } else if (hasBody) { // Body is absent, make an empty body. body = RequestBody.create(null, new byte[0]); } } MediaType contentType = this.contentType; if (contentType != null) { if (body != null) { body = new ContentTypeOverridingRequestBody(body, contentType); } else { requestBuilder.addHeader("Content-Type", contentType.toString()); } } return requestBuilder .url(url) .method(method, body); } private static class ContentTypeOverridingRequestBody extends RequestBody { private final RequestBody delegate; private final MediaType contentType; ContentTypeOverridingRequestBody(RequestBody delegate, MediaType contentType) { this.delegate = delegate; this.contentType = contentType; } @Override public MediaType contentType() { return contentType; } @Override public long contentLength() throws IOException { return delegate.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { delegate.writeTo(sink); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_54_0
crossvul-java_data_bad_4612_4
package org.jooby.handlers; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertNotNull; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.jooby.test.MockUnit; import org.jooby.test.MockUnit.Block; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({AssetHandler.class, File.class, Paths.class, Files.class }) public class AssetHandlerTest { @Test public void customClassloader() throws Exception { URI uri = Paths.get("src", "test", "resources", "org", "jooby").toUri(); new MockUnit(ClassLoader.class) .expect(publicDir(uri, "JoobyTest.js")) .run(unit -> { URL value = new AssetHandler("/", unit.get(ClassLoader.class)) .resolve("JoobyTest.js"); assertNotNull(value); }); } @Test public void shouldCallParentOnMissing() throws Exception { URI uri = Paths.get("src", "test", "resources", "org", "jooby").toUri(); new MockUnit(ClassLoader.class) .expect(publicDir(uri, "index.js", false)) .expect(unit -> { ClassLoader loader = unit.get(ClassLoader.class); expect(loader.getResource("index.js")).andReturn(uri.toURL()); }) .run(unit -> { URL value = new AssetHandler("/", unit.get(ClassLoader.class)) .resolve("index.js"); assertNotNull(value); }); } @Test public void ignoreMalformedURL() throws Exception { Path path = Paths.get("src", "test", "resources", "org", "jooby"); new MockUnit(ClassLoader.class, URI.class) .expect(publicDir(null, "index.js")) .expect(unit -> { URI uri = unit.get(URI.class); expect(uri.toURL()).andThrow(new MalformedURLException()); }) .expect(unit -> { ClassLoader loader = unit.get(ClassLoader.class); expect(loader.getResource("index.js")).andReturn(path.toUri().toURL()); }) .run(unit -> { URL value = new AssetHandler("/", unit.get(ClassLoader.class)) .resolve("index.js"); assertNotNull(value); }); } private Block publicDir(final URI uri, final String name) { return publicDir(uri, name, true); } private Block publicDir(final URI uri, final String name, final boolean exists) { return unit -> { unit.mockStatic(Paths.class); Path basedir = unit.mock(Path.class); expect(Paths.get("public")).andReturn(basedir); Path path = unit.mock(Path.class); expect(basedir.resolve(name)).andReturn(path); expect(path.normalize()).andReturn(path); if (exists) { expect(path.startsWith(basedir)).andReturn(true); } unit.mockStatic(Files.class); expect(Files.exists(basedir)).andReturn(true); expect(Files.exists(path)).andReturn(exists); if (exists) { if (uri != null) { expect(path.toUri()).andReturn(uri); } else { expect(path.toUri()).andReturn(unit.get(URI.class)); } } }; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_4
crossvul-java_data_bad_416_0
package org.linlinjava.litemall.wx.web; import org.linlinjava.litemall.core.storage.StorageService; import org.linlinjava.litemall.core.util.CharUtil; import org.linlinjava.litemall.core.util.ResponseUtil; import org.linlinjava.litemall.db.domain.LitemallStorage; import org.linlinjava.litemall.db.service.LitemallStorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/wx/storage") @Validated public class WxStorageController { @Autowired private StorageService storageService; @Autowired private LitemallStorageService litemallStorageService; private String generateKey(String originalFilename) { int index = originalFilename.lastIndexOf('.'); String suffix = originalFilename.substring(index); String key = null; LitemallStorage storageInfo = null; do { key = CharUtil.getRandomString(20) + suffix; storageInfo = litemallStorageService.findByKey(key); } while (storageInfo != null); return key; } @PostMapping("/upload") public Object upload(@RequestParam("file") MultipartFile file) throws IOException { String originalFilename = file.getOriginalFilename(); String url = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename); Map<String, Object> data = new HashMap<>(); data.put("url", url); return ResponseUtil.ok(data); } @GetMapping("/fetch/{key:.+}") public ResponseEntity<Resource> fetch(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).body(file); } @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_416_0
crossvul-java_data_bad_54_1
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import java.io.IOException; import java.lang.reflect.Method; import java.math.BigInteger; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.Buffer; import org.junit.Test; import retrofit2.helpers.NullObjectConverterFactory; import retrofit2.helpers.ToStringConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.HEAD; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.HeaderMap; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.OPTIONS; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import retrofit2.http.QueryName; import retrofit2.http.Url; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @SuppressWarnings({"UnusedParameters", "unused"}) // Parameters inspected reflectively. public final class RequestFactoryTest { private static final MediaType TEXT_PLAIN = MediaType.get("text/plain"); @Test public void customMethodNoBody() { class Example { @HTTP(method = "CUSTOM1", path = "/foo") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM1"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertThat(request.body()).isNull(); } @Test public void customMethodWithBody() { class Example { @HTTP(method = "CUSTOM2", path = "/foo", hasBody = true) Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("CUSTOM2"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertBody(request.body(), "hi"); } @Test public void onlyOneEncodingIsAllowedMultipartFirst() { class Example { @Multipart // @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void onlyOneEncodingIsAllowedFormEncodingFirst() { class Example { @FormUrlEncoded // @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void invalidPathParam() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Path("hey!") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}." + " Found: hey! (parameter #1)\n for method Example.method"); } } @Test public void pathParamNotAllowedInQuery() throws Exception { class Example { @GET("/foo?bar={bar}") // Call<ResponseBody> method(@Path("bar") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL query string \"bar={bar}\" must not have replace block." + " For dynamic query parameters use @Query.\n for method Example.method"); } } @Test public void multipleParameterAnnotationsNotAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Body @Query("nope") String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method"); } } @interface NonNull {} @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Query("maybe") @NonNull Object o) { return null; } } Request request = buildRequest(Example.class, "yep"); assertThat(request.url().toString()).isEqualTo("http://example.com/?maybe=yep"); } @Test public void twoMethodsFail() { class Example { @PATCH("/foo") // @POST("/foo") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .isIn("Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method", "Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method"); } } @Test public void lackingMethod() { class Example { Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method"); } } @Test public void implicitMultipartForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Part("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitMultipartWithPartMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@PartMap Map<String, String> params) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void multipartFailsOnNonBodyMethod() { class Example { @Multipart // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void multipartFailsWithNoParts() { class Example { @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart method must contain at least one @Part.\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Field("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void formEncodingFailsOnNonBodyMethod() { class Example { @FormUrlEncoded // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void formEncodingFailsWithNoParts() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Form-encoded method must contain at least one @Field.\n for method Example.method"); } } @Test public void headersFailWhenEmptyOnMethod() { class Example { @GET("/") // @Headers({}) // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Headers annotation is empty.\n for method Example.method"); } } @Test public void headersFailWhenMalformed() { class Example { @GET("/") // @Headers("Malformed") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Headers value must be in the form \"Name: Value\". Found: \"Malformed\"\n for method Example.method"); } } @Test public void pathParamNonPathParamAndTypedBytes() { class Example { @PUT("/{a}") // Call<ResponseBody> method(@Path("a") int a, @Path("b") int b, @Body int c) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL \"/{a}\" does not contain \"{b}\". (parameter #2)\n for method Example.method"); } } @Test public void parameterWithoutAnnotation() { class Example { @GET("/") // Call<ResponseBody> method(String a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "No Retrofit annotation found. (parameter #1)\n for method Example.method"); } } @Test public void nonBodyHttpMethodWithSingleEntity() { class Example { @GET("/") // Call<ResponseBody> method(@Body String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Non-body HTTP method cannot contain @Body.\n for method Example.method"); } } @Test public void queryMapMustBeAMap() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void queryMapSupportsSubclasses() { class Foo extends HashMap<String, String> { } class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Foo a) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); assertThat(request.url().toString()).isEqualTo("http://example.com/?hello=world"); } @Test public void queryMapRejectsNull() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map was null."); } } @Test public void queryMapRejectsNullKeys() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } Map<String, String> queryParams = new LinkedHashMap<>(); queryParams.put("ping", "pong"); queryParams.put(null, "kat"); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map contained null key."); } } @Test public void queryMapRejectsNullValues() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } Map<String, String> queryParams = new LinkedHashMap<>(); queryParams.put("ping", "pong"); queryParams.put("kit", null); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map contained null value for key 'kit'."); } } @Test public void getWithHeaderMap() { class Example { @GET("/search") Call<ResponseBody> method(@HeaderMap Map<String, Object> headers) { return null; } } Map<String, Object> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put("Accept-Charset", "utf-8"); Request request = buildRequest(Example.class, headers); assertThat(request.method()).isEqualTo("GET"); assertThat(request.url().toString()).isEqualTo("http://example.com/search"); assertThat(request.body()).isNull(); assertThat(request.headers().size()).isEqualTo(2); assertThat(request.header("Accept")).isEqualTo("text/plain"); assertThat(request.header("Accept-Charset")).isEqualTo("utf-8"); } @Test public void headerMapMustBeAMap() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap List<String> headers) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@HeaderMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void headerMapSupportsSubclasses() { class Foo extends HashMap<String, String> { } class Example { @GET("/search") Call<ResponseBody> method(@HeaderMap Foo headers) { return null; } } Foo headers = new Foo(); headers.put("Accept", "text/plain"); Request request = buildRequest(Example.class, headers); assertThat(request.url().toString()).isEqualTo("http://example.com/search"); assertThat(request.headers().size()).isEqualTo(1); assertThat(request.header("Accept")).isEqualTo("text/plain"); } @Test public void headerMapRejectsNull() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } try { buildRequest(Example.class, (Map<String, String>) null); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map was null."); } } @Test public void headerMapRejectsNullKeys() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } Map<String, String> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put(null, "utf-8"); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map contained null key."); } } @Test public void headerMapRejectsNullValues() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } Map<String, String> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put("Accept-Charset", null); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map contained null value for key 'Accept-Charset'."); } } @Test public void twoBodies() { class Example { @PUT("/") // Call<ResponseBody> method(@Body String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple @Body method annotations found. (parameter #2)\n for method Example.method"); } } @Test public void bodyInNonBodyRequest() { class Example { @Multipart // @PUT("/") // Call<ResponseBody> method(@Part("one") String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method"); } } @Test public void get() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void delete() { class Example { @DELETE("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("DELETE"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertNull(request.body()); } @Test public void head() { class Example { @HEAD("/foo/bar/") // Call<Void> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("HEAD"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headWithoutVoidThrows() { class Example { @HEAD("/foo/bar/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HEAD method must use Void as response type.\n for method Example.method"); } } @Test public void post() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void put() { class Example { @PUT("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PUT"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void patch() { class Example { @PATCH("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PATCH"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void options() { class Example { @OPTIONS("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("OPTIONS"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "po ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void getWithUnusedAndInvalidNamedPathParam() { class Example { @GET("/foo/bar/{ping}/{kit,kat}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/%7Bkit,kat%7D/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "po%20ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathSegments() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/pong/more"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/more/"); assertThat(request.body()).isNull(); } @Test public void getWithUnencodedPathSegmentsPreventsRequestSplitting() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = false) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/\r\nheader: blue"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz%2F%0D%0Aheader:%20blue/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathStillPreventsRequestSplitting() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/\r\npong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/"); assertThat(request.body()).isNull(); } @Test public void pathParamRequired() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Path parameter \"ping\" value must not be null."); } } @Test public void getWithQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query(value = "pi%20ng", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "p%20o%20n%20g"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g"); assertThat(request.body()).isNull(); } @Test public void queryParamOptionalOmitsQuery() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); } @Test public void queryParamOptional() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("foo") String foo, @Query("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?foo=bar&kit=kat"); } @Test public void getWithQueryUrlAndParam() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithQuery() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit, @Query("riff") String riff) { return null; } } Request request = buildRequest(Example.class, "pong", "kat", "raff"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff"); assertThat(request.body()).isNull(); } @Test public void getWithQueryThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Query("kit") String kit, @Path("ping") String ping) { return null; } } try { buildRequest(Example.class, "kat", "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @Query. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryNameThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@QueryName String kit, @Path("ping") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, "kat", "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @QueryName. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryMapThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Path("ping") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @QueryMap. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathAndQueryQuestionMarkParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong?", "kat?"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()) .isEqualTo("http://example.com/foo/bar/pong%3F/?kit=kat%3F"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryAmpersandParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong&", "kat&"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong&/?kit=kat%26"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryHashParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong#", "kat#"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong%23/?kit=kat%23"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") List<Object> keys) { return null; } } List<Object> values = Arrays.<Object>asList(1, 2, null, "three", "1"); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") Object[] keys) { return null; } } Object[] values = { 1, 2, null, "three", "1" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamPrimitiveArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=3&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryNameParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName(encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "p%20o%20n%20g"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?p%20o%20n%20g"); assertThat(request.body()).isNull(); } @Test public void queryNameParamOptionalOmitsQuery() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); } @Test public void getWithQueryNameParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName List<Object> keys) { return null; } } List<Object> values = Arrays.<Object>asList(1, 2, null, "three", "1"); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName Object[] keys) { return null; } } Object[] values = { 1, 2, null, "three", "1" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParamPrimitiveArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&3&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "kat"); params.put("ping", "pong"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=kat&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap(encoded = true) Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "k%20t"); params.put("pi%20ng", "p%20g"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g"); assertThat(request.body()).isNull(); } @Test public void getAbsoluteUrl() { class Example { @GET("http://example2.com/foo/bar/") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrl() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrl() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "https://example2.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("https://example2.com/foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithUrlAbsoluteSameHost() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "http://example.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithHttpUrl() { class Example { @GET Call<ResponseBody> method(@Url HttpUrl url) { return null; } } Request request = buildRequest(Example.class, HttpUrl.get("http://example.com/foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url()).isEqualTo(HttpUrl.get("http://example.com/foo/bar/")); assertThat(request.body()).isNull(); } @Test public void getWithNullUrl() { class Example { @GET Call<ResponseBody> method(@Url HttpUrl url) { return null; } } try { buildRequest(Example.class, (HttpUrl) null); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("@Url parameter is null."); } } @Test public void getWithNonStringUrlThrows() { class Example { @GET Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type." + " (parameter #1)\n" + " for method Example.method"); } } @Test public void getUrlAndUrlParamThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Url cannot be used with @GET URL (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithoutUrlThrows() { class Example { @GET Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Missing either @GET URL or @Url parameter.\n" + " for method Example.method"); } } @Test public void getWithUrlThenPathThrows() { class Example { @GET Call<ResponseBody> method(@Url String url, @Path("hey") String hey) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path parameters may not be used with @Url. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@Path("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path can only be used with relative url on @GET (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithQueryThenUrlThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Query("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "hey", "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @Query. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryNameThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@QueryName String name, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @QueryName. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryMapThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @QueryMap. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithUrlThenQuery() { class Example { @GET Call<ResponseBody> method(@Url String url, @Query("hey") String hey) { return null; } } Request request = buildRequest(Example.class, "foo/bar/", "hey!"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hey=hey%21"); } @Test public void postWithUrl() { class Example { @POST Call<ResponseBody> method(@Url String url, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, "http://example.com/foo/bar", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar"); assertBody(request.body(), "hi"); } @Test public void normalPostWithPathParam() { class Example { @POST("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/"); assertBody(request.body(), "Hi!"); } @Test public void emptyBody() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Test public void customMethodEmptyBody() { class Example { @HTTP(method = "CUSTOM", path = "/foo/bar/", hasBody = true) // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Test public void bodyRequired() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Body parameter value must not be null."); } } @Test public void bodyWithPathParams() { class Example { @POST("/foo/bar/{ping}/{kit}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body, @Path("kit") String kit) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body, "kat"); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/kat/"); assertBody(request.body(), "Hi!"); } @Test public void simpleMultipart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("kit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( TEXT_PLAIN, "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); } @Test public void multipartArray() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String[] ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { new String[] { "pong1", "pong2" } }); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part RequestBody part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartIterableRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part List<RequestBody> part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartArrayRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part RequestBody[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartOkHttpPartForbidsName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("name") MultipartBody.Part part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartOkHttpPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpIterablePart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part List<MultipartBody.Part> part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar"); MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, Arrays.asList(part1, part2)); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"foo\"\r\n") .contains("\r\nbar\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpArrayPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part[] part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar"); MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, new Object[] { new MultipartBody.Part[] { part1, part2 } }); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"foo\"\r\n") .contains("\r\nbar\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpPartWithFilename() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData("kit", "kit.txt", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"; filename=\"kit.txt\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartIterable() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") List<String> ping) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("pong1", "pong2")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartIterableOkHttpPart() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") List<MultipartBody.Part> part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartArrayOkHttpPart() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") MultipartBody.Part[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part(value = "ping", encoding = "8-bit") String ping, @Part(value = "kit", encoding = "7-bit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( TEXT_PLAIN, "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 7-bit") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMap() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMapWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap(encoding = "8-bit") Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMapRejectsNonStringKeys() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<Object, RequestBody> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap keys must be of type String: class java.lang.Object (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartPartMapRejectsOkHttpPartValues() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, MultipartBody.Part> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap values cannot be MultipartBody.Part. Use @Part List<Part> or a different value type instead. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartPartMapRejectsNull() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map was null."); } } @Test public void multipartPartMapRejectsNullKeys() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put(null, RequestBody.create(null, "kat")); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map contained null key."); } } @Test public void multipartPartMapRejectsNullValues() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", null); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map contained null value for key 'kit'."); } } @Test public void multipartPartMapMustBeMap() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap List<Object> parts) { return null; } } try { buildRequest(Example.class, Collections.emptyList()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void multipartPartMapSupportsSubclasses() throws IOException { class Foo extends HashMap<String, String> { } class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Foo parts) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()) .contains("name=\"hello\"") .contains("\r\n\r\nworld\r\n--"); } @Test public void multipartNullRemovesPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("fizz") String fizz) { return null; } } Request request = buildRequest(Example.class, "pong", null); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong\r\n--"); } @Test public void multipartPartOptional() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") RequestBody ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part."); } } @Test public void simpleFormEncoded() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "bar", "pong"); assertBody(request.body(), "foo=bar&ping=pong"); } @Test public void formEncodedWithEncodedNameFieldParam() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field(value = "na%20me", encoded = true) String foo) { return null; } } Request request = buildRequest(Example.class, "ba%20r"); assertBody(request.body(), "na%20me=ba%20r"); } @Test public void formEncodedFieldOptional() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping, @Field("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertBody(request.body(), "foo=bar&kit=kat"); } @Test public void formEncodedFieldList() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") List<Object> fields, @Field("kit") String kit) { return null; } } List<Object> values = Arrays.<Object>asList("foo", "bar", null, 3); Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=foo&foo=bar&foo=3&kit=kat"); } @Test public void formEncodedFieldArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") Object[] fields, @Field("kit") String kit) { return null; } } Object[] values = { 1, 2, null, "three" }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=three&kit=kat"); } @Test public void formEncodedFieldPrimitiveArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") int[] fields, @Field("kit") String kit) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=3&kit=kat"); } @Test public void formEncodedWithEncodedNameFieldParamMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap(encoded = true) Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("k%20it", "k%20at"); fieldMap.put("pin%20g", "po%20ng"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "k%20it=k%20at&pin%20g=po%20ng"); } @Test public void formEncodedFieldMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("ping", "pong"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "kit=kat&ping=pong"); } @Test public void fieldMapRejectsNull() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map was null."); } } @Test public void fieldMapRejectsNullKeys() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put(null, "pong"); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map contained null key."); } } @Test public void fieldMapRejectsNullValues() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("foo", null); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map contained null value for key 'foo'."); } } @Test public void fieldMapMustBeAMap() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void fieldMapSupportsSubclasses() throws IOException { class Foo extends HashMap<String, String> { } class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Foo a) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo("hello=world"); } @Test public void simpleHeaders() { class Example { @GET("/foo/bar/") @Headers({ "ping: pong", "kit: kat" }) Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headersDoNotOverwriteEachOther() { class Example { @GET("/foo/bar/") @Headers({ "ping: pong", "kit: kat", "kit: -kat", }) Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(3); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.values("kit")).containsOnly("kat", "-kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamToString() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("kit") BigInteger kit) { return null; } } Request request = buildRequest(Example.class, new BigInteger("1234")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(1); assertThat(headers.get("kit")).isEqualTo("1234"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParam() { class Example { @GET("/foo/bar/") // @Headers("ping: pong") // Call<ResponseBody> method(@Header("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "kat"); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") List<String> kit) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("bar", null, "baz")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") String[] kit) { return null; } } Request request = buildRequest(Example.class, (Object) new String[] { "bar", null, "baz" }); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void contentTypeAnnotationHeaderOverrides() { class Example { @POST("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } @Test public void malformedContentTypeHeaderThrows() { class Example { @POST("/") // @Headers("Content-Type: hello, world!") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); try { buildRequest(Example.class, body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Malformed content type: hello, world!\n" + " for method Example.method"); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } @Test public void contentTypeAnnotationHeaderAddsHeaderWithNoBody() { class Example { @DELETE("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.headers().get("Content-Type")).isEqualTo("text/not-plain"); } @Test public void contentTypeParameterHeaderOverrides() { class Example { @POST("/") // Call<ResponseBody> method(@Header("Content-Type") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Plain"); Request request = buildRequest(Example.class, "text/not-plain", body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } @Test public void malformedContentTypeParameterThrows() { class Example { @POST("/") // Call<ResponseBody> method(@Header("Content-Type") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); try { buildRequest(Example.class, "hello, world!", body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Malformed content type: hello, world!"); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } @Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET("ftp://example.org") Call<ResponseBody> get() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Malformed URL. Base: http://example.com/, Relative: ftp://example.org"); } } @Test public void malformedParameterRelativeUrlThrows() { class Example { @GET Call<ResponseBody> get(@Url String relativeUrl) { return null; } } try { buildRequest(Example.class, "ftp://example.org"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Malformed URL. Base: http://example.com/, Relative: ftp://example.org"); } } @Test public void multipartPartsShouldBeInOrder() throws IOException { class Example { @Multipart @POST("/foo") Call<ResponseBody> get(@Part("first") String data, @Part("second") String dataTwo, @Part("third") String dataThree) { return null; } } Request request = buildRequest(Example.class, "firstParam", "secondParam", "thirdParam"); MultipartBody body = (MultipartBody) request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String readBody = buffer.readUtf8(); assertThat(readBody.indexOf("firstParam")).isLessThan(readBody.indexOf("secondParam")); assertThat(readBody.indexOf("secondParam")).isLessThan(readBody.indexOf("thirdParam")); } @Test public void queryParamsSkippedIfConvertedToNull() throws Exception { class Example { @GET("/query") Call<ResponseBody> queryPath(@Query("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); assertThat(request.url().toString()).doesNotContain("Ignored"); } @Test public void queryParamMapsConvertedToNullShouldError() throws Exception { class Example { @GET("/query") Call<ResponseBody> queryPath(@QueryMap Map<String, String> a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Map<String, String> queryMap = Collections.singletonMap("kit", "kat"); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( "Query map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'."); } } @Test public void fieldParamsSkippedIfConvertedToNull() throws Exception { class Example { @FormUrlEncoded @POST("/query") Call<ResponseBody> queryPath(@Field("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); assertThat(request.url().toString()).doesNotContain("Ignored"); } @Test public void fieldParamMapsConvertedToNullShouldError() throws Exception { class Example { @FormUrlEncoded @POST("/query") Call<ResponseBody> queryPath(@FieldMap Map<String, String> a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Map<String, String> queryMap = Collections.singletonMap("kit", "kat"); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( "Field map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'."); } } private static void assertBody(RequestBody body, String expected) { assertThat(body).isNotNull(); Buffer buffer = new Buffer(); try { body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } } static <T> Request buildRequest(Class<T> cls, Retrofit.Builder builder, Object... args) { okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() { @Override public okhttp3.Call newCall(Request request) { throw new UnsupportedOperationException("Not implemented"); } }; Retrofit retrofit = builder.callFactory(callFactory).build(); Method method = TestingUtils.onlyMethod(cls); try { return RequestFactory.parseAnnotations(retrofit, method).create(args); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } } static <T> Request buildRequest(Class<T> cls, Object... args) { Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com/") .addConverterFactory(new ToStringConverterFactory()); return buildRequest(cls, retrofitBuilder, args); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_54_1
crossvul-java_data_bad_1883_3
package eu.hinsch.spring.boot.actuator.logview; import org.apache.catalina.ssi.ByteArrayServletOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") public class LogViewEndpointTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private HttpServletResponse response; private LogViewEndpoint logViewEndpoint; private Model model; private long now; @Before public void setUp() { MockitoAnnotations.initMocks(this); logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(), new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets()); model = new ExtendedModelMap(); now = new Date().getTime(); } @Test public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.containsAttribute("files"), is(true)); assertThat(getFileEntries(), hasSize(0)); } @Test public void shouldListSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileNames(), contains("A.log", "B.log", "C.log")); } @Test public void shouldListReverseSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, true, null); // then assertThat(getFileNames(), contains("C.log", "B.log", "A.log")); } @Test public void shouldListSortedBySize() throws Exception { // given createFile("A.log", "xx", now); createFile("B.log", "x", now); createFile("C.log", "xxx", now); // when logViewEndpoint.list(model, SortBy.SIZE, false, null); // then assertThat(getFileNames(), contains("B.log", "A.log", "C.log")); assertThat(getFileSizes(), contains(1L, 2L, 3L)); } @Test public void shouldListSortedByDate() throws Exception { // given // TODO java 8 date api createFile("A.log", "x", now); createFile("B.log", "x", now - 10 * 60 * 1000); createFile("C.log", "x", now - 5 * 60 * 1000); // when logViewEndpoint.list(model, SortBy.MODIFIED, false, null); // then assertThat(getFileNames(), contains("B.log", "C.log", "A.log")); assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago")); } @Test public void shouldSetFileTypeForFile() throws Exception { // given createFile("A.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE)); } @Test public void shouldSetFileTypeForArchive() throws Exception { // given createFile("A.log.tar.gz", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE)); } @Test public void shouldContainEmptyParentLinkInBaseFolder() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder"); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); temporaryFolder.newFolder("subfolder", "nested"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested"); // then assertThat(model.asMap().get("parent"), is("/subfolder")); } @Test public void shouldIncludeSubfolderEntry() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY)); assertThat(fileEntry.getFilename(), is("subfolder")); } @Test public void shouldListZipContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewZipFileContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.zip", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) { ZipEntry zipEntry = new ZipEntry(contentFileName); zos.putNextEntry(zipEntry); IOUtils.write(content, zos); } } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForZip() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.zip", 1, response); // then -> exception } @Test public void shouldListTarGzContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewTarGzFileContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.tar.gz", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.tar.gz", 1, response); // then -> exception } private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream( new BufferedOutputStream(new FileOutputStream( new File(temporaryFolder.getRoot(), archiveFileName)))))) { tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName); archiveEntry.setSize(content.length()); tos.putArchiveEntry(archiveEntry); IOUtils.write(content, tos); tos.closeArchiveEntry(); } } @Test public void shouldRedirectWithoutTrainingSlash() throws IOException { // when logViewEndpoint.redirect(response); // then verify(response).sendRedirect("log/"); } @Test public void shouldEndpointBeSensitive() { assertThat(logViewEndpoint.isSensitive(), is(true)); } @Test public void shouldReturnContextPath() { assertThat(logViewEndpoint.getPath(), is("/log")); } @Test public void shouldReturnNullEndpointType() { assertThat(logViewEndpoint.getEndpointType(), is(nullValue())); } @Test public void shouldNotAllowToListFileOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("this String argument must not contain the substring [..]")); // when logViewEndpoint.view("../somefile", null, null, null); } @Test public void shouldViewFile() throws Exception { // given createFile("file.log", "abc", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, null, response); // then assertThat(new String(outputStream.toByteArray()), is("abc")); } @Test public void shouldTailViewOnlyLastLine() throws Exception { // given createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, 1, response); // then assertThat(new String(outputStream.toByteArray()), not(containsString("line1"))); assertThat(new String(outputStream.toByteArray()), containsString("line2")); } @Test public void shouldSearchInFiles() throws Exception { // given String sep = System.lineSeparator(); createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1); createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.search("line2", response); // then String output = new String(outputStream.toByteArray()); assertThat(output, containsString("[A.log] A-line2")); assertThat(output, containsString("[B.log] B-line2")); assertThat(output, not(containsString("line1"))); assertThat(output, not(containsString("line3"))); } private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception { ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); return outputStream; } private List<String> getFileNames() { return getFileEntries() .stream() .map(FileEntry::getFilename) .collect(toList()); } private List<Long> getFileSizes() { return getFileEntries() .stream() .map(FileEntry::getSize) .collect(toList()); } private List<String> getFilePrettyTimes() { return getFileEntries() .stream() .map(FileEntry::getModifiedPretty) .collect(toList()); } private List<FileEntry> getFileEntries() { return (List<FileEntry>) model.asMap().get("files"); } private void createFile(String filename, String content, long modified) throws Exception { File file = new File(temporaryFolder.getRoot(), filename); FileUtils.write(file, content); assertThat(file.setLastModified(modified), is(true)); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_1883_3
crossvul-java_data_good_688_1
package spark.embeddedserver.jetty; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.After; import org.junit.Test; import spark.embeddedserver.EmbeddedServer; import spark.route.Routes; import spark.staticfiles.StaticFilesConfiguration; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class EmbeddedJettyFactoryTest { private EmbeddedServer embeddedServer; @Test public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6757, null, 100, 10, 10000); verify(jettyServerFactory, times(1)).create(100, 10, 10000); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withThreadPool() throws Exception { final QueuedThreadPool threadPool = new QueuedThreadPool(100); final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool)); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6758, null, 0, 0, 0); verify(jettyServerFactory, times(1)).create(threadPool); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 6759, null, 100, 10, 10000); verify(jettyServerFactory, times(1)).create(100, 10, 10000); verifyNoMoreInteractions(jettyServerFactory); } @After public void tearDown() throws Exception { if (embeddedServer != null) { embeddedServer.extinguish(); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_688_1
crossvul-java_data_bad_689_2
/* * Copyright 2011- Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.examples.staticresources; import static spark.Spark.get; import static spark.Spark.staticFileLocation; /** * Example showing how serve static resources. */ public class StaticResources { public static void main(String[] args) { // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes. staticFileLocation("/public"); get("/hello", (request, response) -> { return "Hello World!"; }); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_689_2
crossvul-java_data_bad_690_1
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) * * @return if exists. */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) * * @return the input stream. */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) * * @return the url. */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @see spark.utils.StringUtils#applyRelativePath(String, String) * * @return the resource. */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @see spark.utils.StringUtils#getFilename(String) * * @return the file name. */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_690_1
crossvul-java_data_good_690_1
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } private static boolean doesNotContainFileColon(String path) { return !path.contains("file:"); } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @return if exists. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @return the input stream. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @return the url. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @return the resource. * @see spark.utils.StringUtils#applyRelativePath(String, String) */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @return the file name. * @see spark.utils.StringUtils#getFilename(String) */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_690_1
crossvul-java_data_good_4612_4
package org.jooby.handlers; import org.jooby.Route; import org.jooby.test.MockUnit; import org.jooby.test.MockUnit.Block; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertNotNull; @RunWith(PowerMockRunner.class) @PrepareForTest({AssetHandler.class, File.class, Paths.class, Files.class}) public class AssetHandlerTest { @Test public void customClassloader() throws Exception { URI uri = Paths.get("src", "test", "resources", "org", "jooby").toUri(); new MockUnit(ClassLoader.class) .expect(publicDir(uri, "JoobyTest.js")) .run(unit -> { URL value = newHandler(unit, "/") .resolve("JoobyTest.js"); assertNotNull(value); }); } private AssetHandler newHandler(MockUnit unit, String location) { AssetHandler handler = new AssetHandler(location, unit.get(ClassLoader.class)); new Route.AssetDefinition("GET", "/assets/**", handler, false); return handler; } @Test public void shouldCallParentOnMissing() throws Exception { URI uri = Paths.get("src", "test", "resources", "org", "jooby").toUri(); new MockUnit(ClassLoader.class) .expect(publicDir(uri, "assets/index.js", false)) .expect(unit -> { ClassLoader loader = unit.get(ClassLoader.class); expect(loader.getResource("assets/index.js")).andReturn(uri.toURL()); }) .run(unit -> { URL value = newHandler(unit, "/") .resolve("assets/index.js"); assertNotNull(value); }); } @Test public void ignoreMalformedURL() throws Exception { Path path = Paths.get("src", "test", "resources", "org", "jooby"); new MockUnit(ClassLoader.class, URI.class) .expect(publicDir(null, "assets/index.js")) .expect(unit -> { URI uri = unit.get(URI.class); expect(uri.toURL()).andThrow(new MalformedURLException()); }) .expect(unit -> { ClassLoader loader = unit.get(ClassLoader.class); expect(loader.getResource("assets/index.js")).andReturn(path.toUri().toURL()); }) .run(unit -> { URL value = newHandler(unit, "/") .resolve("assets/index.js"); assertNotNull(value); }); } private Block publicDir(final URI uri, final String name) { return publicDir(uri, name, true); } private Block publicDir(final URI uri, final String name, final boolean exists) { return unit -> { unit.mockStatic(Paths.class); Path basedir = unit.mock(Path.class); expect(Paths.get("public")).andReturn(basedir); Path path = unit.mock(Path.class); expect(basedir.resolve(name)).andReturn(path); expect(path.normalize()).andReturn(path); if (exists) { expect(path.startsWith(basedir)).andReturn(true); } unit.mockStatic(Files.class); expect(Files.exists(basedir)).andReturn(true); expect(Files.exists(path)).andReturn(exists); if (exists) { if (uri != null) { expect(path.toUri()).andReturn(uri); } else { expect(path.toUri()).andReturn(unit.get(URI.class)); } } }; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_4
crossvul-java_data_good_688_0
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.ResourceUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.isTrue(isValid(path), "Path is not valid"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } private static boolean isValid(final String path) { return !isInvalidPath(path); } private static boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { return true; } if (path.contains(":/")) { String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path); if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) { return true; } } if (path.contains("")) { path = StringUtils.cleanPath(path); if (path.contains("../")) { return true; } } return false; } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @return if exists. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @return the input stream. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @return the url. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @return the resource. * @see spark.utils.StringUtils#applyRelativePath(String, String) */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @return the file name. * @see spark.utils.StringUtils#getFilename(String) */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_688_0
crossvul-java_data_bad_1884_3
package eu.hinsch.spring.boot.actuator.logview; import org.apache.catalina.ssi.ByteArrayServletOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") public class LogViewEndpointTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private HttpServletResponse response; private LogViewEndpoint logViewEndpoint; private Model model; private long now; @Before public void setUp() { MockitoAnnotations.initMocks(this); logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(), new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets()); model = new ExtendedModelMap(); now = new Date().getTime(); } @Test public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.containsAttribute("files"), is(true)); assertThat(getFileEntries(), hasSize(0)); } @Test public void shouldListSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileNames(), contains("A.log", "B.log", "C.log")); } @Test public void shouldListReverseSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, true, null); // then assertThat(getFileNames(), contains("C.log", "B.log", "A.log")); } @Test public void shouldListSortedBySize() throws Exception { // given createFile("A.log", "xx", now); createFile("B.log", "x", now); createFile("C.log", "xxx", now); // when logViewEndpoint.list(model, SortBy.SIZE, false, null); // then assertThat(getFileNames(), contains("B.log", "A.log", "C.log")); assertThat(getFileSizes(), contains(1L, 2L, 3L)); } @Test public void shouldListSortedByDate() throws Exception { // given // TODO java 8 date api createFile("A.log", "x", now); createFile("B.log", "x", now - 10 * 60 * 1000); createFile("C.log", "x", now - 5 * 60 * 1000); // when logViewEndpoint.list(model, SortBy.MODIFIED, false, null); // then assertThat(getFileNames(), contains("B.log", "C.log", "A.log")); assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago")); } @Test public void shouldSetFileTypeForFile() throws Exception { // given createFile("A.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE)); } @Test public void shouldSetFileTypeForArchive() throws Exception { // given createFile("A.log.tar.gz", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE)); } @Test public void shouldContainEmptyParentLinkInBaseFolder() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder"); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); temporaryFolder.newFolder("subfolder", "nested"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested"); // then assertThat(model.asMap().get("parent"), is("/subfolder")); } @Test public void shouldIncludeSubfolderEntry() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY)); assertThat(fileEntry.getFilename(), is("subfolder")); } @Test public void shouldListZipContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewZipFileContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.zip", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) { ZipEntry zipEntry = new ZipEntry(contentFileName); zos.putNextEntry(zipEntry); IOUtils.write(content, zos); } } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForZip() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.zip", 1, response); // then -> exception } @Test public void shouldListTarGzContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewTarGzFileContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.tar.gz", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.tar.gz", 1, response); // then -> exception } private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream( new BufferedOutputStream(new FileOutputStream( new File(temporaryFolder.getRoot(), archiveFileName)))))) { tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName); archiveEntry.setSize(content.length()); tos.putArchiveEntry(archiveEntry); IOUtils.write(content, tos); tos.closeArchiveEntry(); } } @Test public void shouldRedirectWithoutTrainingSlash() throws IOException { // when logViewEndpoint.redirect(response); // then verify(response).sendRedirect("log/"); } @Test public void shouldEndpointBeSensitive() { assertThat(logViewEndpoint.isSensitive(), is(true)); } @Test public void shouldReturnContextPath() { assertThat(logViewEndpoint.getPath(), is("/log")); } @Test public void shouldReturnNullEndpointType() { assertThat(logViewEndpoint.getEndpointType(), is(nullValue())); } @Test public void shouldNotAllowToListFileOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("this String argument must not contain the substring [..]")); // when logViewEndpoint.view("../somefile", null, null, null); } @Test public void shouldViewFile() throws Exception { // given createFile("file.log", "abc", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, null, response); // then assertThat(new String(outputStream.toByteArray()), is("abc")); } @Test public void shouldTailViewOnlyLastLine() throws Exception { // given createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, 1, response); // then assertThat(new String(outputStream.toByteArray()), not(containsString("line1"))); assertThat(new String(outputStream.toByteArray()), containsString("line2")); } @Test public void shouldSearchInFiles() throws Exception { // given String sep = System.lineSeparator(); createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1); createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.search("line2", response); // then String output = new String(outputStream.toByteArray()); assertThat(output, containsString("[A.log] A-line2")); assertThat(output, containsString("[B.log] B-line2")); assertThat(output, not(containsString("line1"))); assertThat(output, not(containsString("line3"))); } private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception { ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); return outputStream; } private List<String> getFileNames() { return getFileEntries() .stream() .map(FileEntry::getFilename) .collect(toList()); } private List<Long> getFileSizes() { return getFileEntries() .stream() .map(FileEntry::getSize) .collect(toList()); } private List<String> getFilePrettyTimes() { return getFileEntries() .stream() .map(FileEntry::getModifiedPretty) .collect(toList()); } private List<FileEntry> getFileEntries() { return (List<FileEntry>) model.asMap().get("files"); } private void createFile(String filename, String content, long modified) throws Exception { File file = new File(temporaryFolder.getRoot(), filename); FileUtils.write(file, content); assertThat(file.setLastModified(modified), is(true)); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_1884_3
crossvul-java_data_bad_1883_2
package eu.hinsch.spring.boot.actuator.logview; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.ui.Model; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; /** * Created by lh on 23/02/15. */ public class LogViewEndpoint implements MvcEndpoint{ private final List<FileProvider> fileProviders; private final Configuration freemarkerConfig; private final String loggingPath; private final List<String> stylesheets; public LogViewEndpoint(String loggingPath, List<String> stylesheets) { this.loggingPath = loggingPath; this.stylesheets = stylesheets; fileProviders = asList(new FileSystemFileProvider(), new ZipArchiveFileProvider(), new TarGzArchiveFileProvider()); freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); } @RequestMapping public void redirect(HttpServletResponse response) throws IOException { response.sendRedirect("log/"); } @RequestMapping("/") @ResponseBody public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { securityCheck(base); Path currentFolder = loggingPath(base); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); } private FileProvider getFileProvider(Path folder) { return fileProviders.stream() .filter(provider -> provider.canHandle(folder)) .findFirst() .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString())); } private String getParent(Path loggingPath) { Path basePath = loggingPath(null); String parent = ""; if (!basePath.toString().equals(loggingPath.toString())) { parent = loggingPath.getParent().toString(); if (parent.startsWith(basePath.toString())) { parent = parent.substring(basePath.toString().length()); } } return parent; } private Path loggingPath(String base) { return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath); } private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) { Comparator<FileEntry> comparator = null; switch (sortBy) { case FILENAME: comparator = (a, b) -> a.getFilename().compareTo(b.getFilename()); break; case SIZE: comparator = (a, b) -> Long.compare(a.getSize(), b.getSize()); break; case MODIFIED: comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis()); break; } List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList()); if (desc) { Collections.reverse(sortedFiles); } return sortedFiles; } @RequestMapping("/view") public void view(@RequestParam String filename, @RequestParam(required = false) String base, @RequestParam(required = false) Integer tailLines, HttpServletResponse response) throws IOException { securityCheck(filename); response.setContentType(MediaType.TEXT_PLAIN_VALUE); Path path = loggingPath(base); FileProvider fileProvider = getFileProvider(path); if (tailLines != null) { fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines); } else { fileProvider.streamContent(path, filename, response.getOutputStream()); } } @RequestMapping("/search") public void search(@RequestParam String term, HttpServletResponse response) throws IOException { Path folder = loggingPath(null); List<FileEntry> files = getFileProvider(folder).getFileEntries(folder); List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false); response.setContentType(MediaType.TEXT_PLAIN_VALUE); ServletOutputStream outputStream = response.getOutputStream(); sortedFiles.stream() .filter(file -> file.getFileType().equals(FileType.FILE)) .forEach(file -> searchAndStreamFile(file, term, outputStream)); } private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) { Path folder = loggingPath(null); try { List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename()))) .stream() .filter(line -> line.contains(term)) .map(line -> "[" + fileEntry.getFilename() + "] " + line) .collect(toList()); for (String line : lines) { outputStream.write(line.getBytes()); outputStream.write(System.lineSeparator().getBytes()); } } catch (IOException e) { throw new RuntimeException("error reading file", e); } } private void securityCheck(String filename) { Assert.doesNotContain(filename, ".."); } @Override public String getPath() { return "/log"; } @Override public boolean isSensitive() { return true; } @Override public Class<? extends Endpoint> getEndpointType() { return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_1883_2
crossvul-java_data_bad_498_2
package cc.mrbird.common.handler; import cc.mrbird.common.domain.ResponseBo; import cc.mrbird.common.exception.LimitAccessException; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.session.ExpiredSessionException; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice @Order(value = Ordered.HIGHEST_PRECEDENCE) public class GlobalExceptionHandler { @ExceptionHandler(value = AuthorizationException.class) public Object handleAuthorizationException(HttpServletRequest request) { if (isAjaxRequest(request)) { return ResponseBo.error("暂无权限,请联系管理员!"); } else { ModelAndView mav = new ModelAndView(); mav.setViewName("error/403"); return mav; } } @ExceptionHandler(value = ExpiredSessionException.class) public String handleExpiredSessionException() { return "login"; } @ExceptionHandler(value = LimitAccessException.class) public ResponseBo handleLimitAccessException(LimitAccessException e) { return ResponseBo.error(e.getMessage()); } private static boolean isAjaxRequest(HttpServletRequest request) { return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_498_2
crossvul-java_data_good_68_1
package org.zeroturnaround.zip; /** * Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import junit.framework.TestCase; public class DirectoryTraversalMaliciousTest extends TestCase { /* * This is the contents of the file. There is one evil file that tries to get out of the * target. * * $ unzip -t zip-slip.zip * Archive: zip-slip.zip * testing: good.txt OK * testing: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt OK * No errors detected in compressed data of zip-slip.zip. */ private static final File badFile = new File("src/test/resources/zip-malicious-traversal.zip"); private static final File badFileBackslashes = new File("src/test/resources/zip-malicious-traversal-backslashes.zip"); public void testUnpackDoesntLeaveTarget() throws Exception { File file = File.createTempFile("temp", null); File tmpDir = file.getParentFile(); try { ZipUtil.unpack(badFile, tmpDir); fail(); } catch (ZipException e) { assertTrue(true); } } public void testUnwrapDoesntLeaveTarget() throws Exception { File file = File.createTempFile("temp", null); File tmpDir = file.getParentFile(); try { ZipUtil.iterate(badFileBackslashes, new ZipUtil.BackslashUnpacker(tmpDir)); fail(); } catch (ZipException e) { assertTrue(true); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_68_1
crossvul-java_data_bad_1884_2
package eu.hinsch.spring.boot.actuator.logview; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.ui.Model; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; /** * Created by lh on 23/02/15. */ public class LogViewEndpoint implements MvcEndpoint{ private final List<FileProvider> fileProviders; private final Configuration freemarkerConfig; private final String loggingPath; private final List<String> stylesheets; public LogViewEndpoint(String loggingPath, List<String> stylesheets) { this.loggingPath = loggingPath; this.stylesheets = stylesheets; fileProviders = asList(new FileSystemFileProvider(), new ZipArchiveFileProvider(), new TarGzArchiveFileProvider()); freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); } @RequestMapping public void redirect(HttpServletResponse response) throws IOException { response.sendRedirect("log/"); } @RequestMapping("/") @ResponseBody public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { securityCheck(base); Path currentFolder = loggingPath(base); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); } private FileProvider getFileProvider(Path folder) { return fileProviders.stream() .filter(provider -> provider.canHandle(folder)) .findFirst() .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString())); } private String getParent(Path loggingPath) { Path basePath = loggingPath(null); String parent = ""; if (!basePath.toString().equals(loggingPath.toString())) { parent = loggingPath.getParent().toString(); if (parent.startsWith(basePath.toString())) { parent = parent.substring(basePath.toString().length()); } } return parent; } private Path loggingPath(String base) { return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath); } private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) { Comparator<FileEntry> comparator = null; switch (sortBy) { case FILENAME: comparator = (a, b) -> a.getFilename().compareTo(b.getFilename()); break; case SIZE: comparator = (a, b) -> Long.compare(a.getSize(), b.getSize()); break; case MODIFIED: comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis()); break; } List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList()); if (desc) { Collections.reverse(sortedFiles); } return sortedFiles; } @RequestMapping("/view") public void view(@RequestParam String filename, @RequestParam(required = false) String base, @RequestParam(required = false) Integer tailLines, HttpServletResponse response) throws IOException { securityCheck(filename); response.setContentType(MediaType.TEXT_PLAIN_VALUE); Path path = loggingPath(base); FileProvider fileProvider = getFileProvider(path); if (tailLines != null) { fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines); } else { fileProvider.streamContent(path, filename, response.getOutputStream()); } } @RequestMapping("/search") public void search(@RequestParam String term, HttpServletResponse response) throws IOException { Path folder = loggingPath(null); List<FileEntry> files = getFileProvider(folder).getFileEntries(folder); List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false); response.setContentType(MediaType.TEXT_PLAIN_VALUE); ServletOutputStream outputStream = response.getOutputStream(); sortedFiles.stream() .filter(file -> file.getFileType().equals(FileType.FILE)) .forEach(file -> searchAndStreamFile(file, term, outputStream)); } private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) { Path folder = loggingPath(null); try { List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename()))) .stream() .filter(line -> line.contains(term)) .map(line -> "[" + fileEntry.getFilename() + "] " + line) .collect(toList()); for (String line : lines) { outputStream.write(line.getBytes()); outputStream.write(System.lineSeparator().getBytes()); } } catch (IOException e) { throw new RuntimeException("error reading file", e); } } private void securityCheck(String filename) { Assert.doesNotContain(filename, ".."); } @Override public String getPath() { return "/log"; } @Override public boolean isSensitive() { return true; } @Override public Class<? extends Endpoint> getEndpointType() { return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_1884_2
crossvul-java_data_bad_67_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_67_1
crossvul-java_data_good_67_0
/** * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.plexus.archiver; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.codehaus.plexus.archiver.util.ArchiveEntryUtils; import org.codehaus.plexus.components.io.attributes.SymlinkUtils; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; /** * @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a> * @todo there should really be constructors which take the source file. */ public abstract class AbstractUnArchiver extends AbstractLogEnabled implements UnArchiver, FinalizerEnabled { private File destDirectory; private File destFile; private File sourceFile; private boolean overwrite = true; private List finalizers; private FileSelector[] fileSelectors; /** * since 2.3 is on by default * * @since 1.1 */ private boolean useJvmChmod = true; /** * @since 1.1 */ private boolean ignorePermissions = false; public AbstractUnArchiver() { // no op } public AbstractUnArchiver( final File sourceFile ) { this.sourceFile = sourceFile; } @Override public File getDestDirectory() { return destDirectory; } @Override public void setDestDirectory( final File destDirectory ) { this.destDirectory = destDirectory; } @Override public File getDestFile() { return destFile; } @Override public void setDestFile( final File destFile ) { this.destFile = destFile; } @Override public File getSourceFile() { return sourceFile; } @Override public void setSourceFile( final File sourceFile ) { this.sourceFile = sourceFile; } @Override public boolean isOverwrite() { return overwrite; } @Override public void setOverwrite( final boolean b ) { overwrite = b; } @Override public final void extract() throws ArchiverException { validate(); execute(); runArchiveFinalizers(); } @Override public final void extract( final String path, final File outputDirectory ) throws ArchiverException { validate( path, outputDirectory ); execute( path, outputDirectory ); runArchiveFinalizers(); } @Override public void addArchiveFinalizer( final ArchiveFinalizer finalizer ) { if ( finalizers == null ) { finalizers = new ArrayList(); } finalizers.add( finalizer ); } @Override public void setArchiveFinalizers( final List archiveFinalizers ) { finalizers = archiveFinalizers; } private void runArchiveFinalizers() throws ArchiverException { if ( finalizers != null ) { for ( Object finalizer1 : finalizers ) { final ArchiveFinalizer finalizer = (ArchiveFinalizer) finalizer1; finalizer.finalizeArchiveExtraction( this ); } } } protected void validate( final String path, final File outputDirectory ) { } protected void validate() throws ArchiverException { if ( sourceFile == null ) { throw new ArchiverException( "The source file isn't defined." ); } if ( sourceFile.isDirectory() ) { throw new ArchiverException( "The source must not be a directory." ); } if ( !sourceFile.exists() ) { throw new ArchiverException( "The source file " + sourceFile + " doesn't exist." ); } if ( destDirectory == null && destFile == null ) { throw new ArchiverException( "The destination isn't defined." ); } if ( destDirectory != null && destFile != null ) { throw new ArchiverException( "You must choose between a destination directory and a destination file." ); } if ( destDirectory != null && !destDirectory.isDirectory() ) { destFile = destDirectory; destDirectory = null; } if ( destFile != null && destFile.isDirectory() ) { destDirectory = destFile; destFile = null; } } @Override public void setFileSelectors( final FileSelector[] fileSelectors ) { this.fileSelectors = fileSelectors; } @Override public FileSelector[] getFileSelectors() { return fileSelectors; } protected boolean isSelected( final String fileName, final PlexusIoResource fileInfo ) throws ArchiverException { if ( fileSelectors != null ) { for ( FileSelector fileSelector : fileSelectors ) { try { if ( !fileSelector.isSelected( fileInfo ) ) { return false; } } catch ( final IOException e ) { throw new ArchiverException( "Failed to check, whether " + fileInfo.getName() + " is selected: " + e.getMessage(), e ); } } } return true; } protected abstract void execute() throws ArchiverException; protected abstract void execute( String path, File outputDirectory ) throws ArchiverException; /** * @since 1.1 */ @Override public boolean isUseJvmChmod() { return useJvmChmod; } /** * <b>jvm chmod won't set group level permissions !</b> * * @since 1.1 */ @Override public void setUseJvmChmod( final boolean useJvmChmod ) { this.useJvmChmod = useJvmChmod; } /** * @since 1.1 */ @Override public boolean isIgnorePermissions() { return ignorePermissions; } /** * @since 1.1 */ @Override public void setIgnorePermissions( final boolean ignorePermissions ) { this.ignorePermissions = ignorePermissions; } protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, final String entryName, final Date entryDate, final boolean isDirectory, final Integer mode, String symlinkDestination ) throws IOException, ArchiverException { // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... final File f = FileUtils.resolveFile( dir, entryName ); // Make sure that the resolved path of the extracted file doesn't escape the destination directory String canonicalDirPath = dir.getCanonicalPath(); String canonicalDestPath = f.getCanonicalPath(); if ( !canonicalDestPath.startsWith( canonicalDirPath ) ) { throw new ArchiverException( "Entry is outside of the target directory (" + entryName + ")" ); } try { if ( !isOverwrite() && f.exists() && ( f.lastModified() >= entryDate.getTime() ) ) { return; } // create intermediary directories - sometimes zip don't add them final File dirF = f.getParentFile(); if ( dirF != null ) { dirF.mkdirs(); } if ( !StringUtils.isEmpty( symlinkDestination ) ) { SymlinkUtils.createSymbolicLink( f, new File( symlinkDestination ) ); } else if ( isDirectory ) { f.mkdirs(); } else { OutputStream out = null; try { out = new FileOutputStream( f ); IOUtil.copy( compressedInputStream, out ); out.close(); out = null; } finally { IOUtil.close( out ); } } f.setLastModified( entryDate.getTime() ); if ( !isIgnorePermissions() && mode != null && !isDirectory ) { ArchiveEntryUtils.chmod( f, mode ); } } catch ( final FileNotFoundException ex ) { getLogger().warn( "Unable to expand to file " + f.getPath() ); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_67_0
crossvul-java_data_bad_256_1
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.application.resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Stream; import javax.faces.application.ProjectStage; import javax.faces.application.ResourceHandler; import javax.faces.application.ResourceVisitOption; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.Util; /** * This class is used to lookup {@link ResourceInfo} instances * and cache any that are successfully looked up to reduce the * computational overhead with the scanning/version checking. * * @since 2.0 */ public class ResourceManager { private static final Logger LOGGER = FacesLogger.RESOURCE.getLogger(); /** * {@link Pattern} for valid mime types to configure compression. */ private static final Pattern CONFIG_MIMETYPE_PATTERN = Pattern.compile("[a-z-]*/[a-z0-9.\\*-]*"); private FaceletWebappResourceHelper faceletWebappResourceHelper = new FaceletWebappResourceHelper(); /** * {@link ResourceHelper} used for looking up webapp-based resources. */ private ResourceHelper webappResourceHelper = new WebappResourceHelper(); /** * {@link ResourceHelper} used for looking up classpath-based resources. */ private ClasspathResourceHelper classpathResourceHelper = new ClasspathResourceHelper(); /** * Cache for storing {@link ResourceInfo} instances to reduce the cost * of the resource lookups. */ private ResourceCache cache; /** * Patterns used to find {@link ResourceInfo} instances that may have their * content compressed. */ private List<Pattern> compressableTypes; /** * This lock is used to ensure the lookup of compressable {@link ResourceInfo} * instances are atomic to prevent theading issues when writing the compressed * content during a lookup. */ private ReentrantLock lock = new ReentrantLock(); // ------------------------------------------------------------ Constructors /* * This ctor is only ever called by test code. */ public ResourceManager(ResourceCache cache) { this.cache = cache; Map<String, Object> throwAwayMap = new HashMap<>(); initCompressableTypes(throwAwayMap); } /** * Constructs a new <code>ResourceManager</code>. Note: if the current * {@link ProjectStage} is {@link ProjectStage#Development} caching or * {@link ResourceInfo} instances will not occur. */ public ResourceManager(Map<String, Object> appMap, ResourceCache cache) { this.cache = cache; initCompressableTypes(appMap); } // ------------------------------------------------------ Public Methods /** * <p> * Attempt to lookup a {@link ResourceInfo} based on the specified * <code>libraryName<code> and <code>resourceName</code> * </p> * * <p> * Implementation Note: Synchronization is necessary when looking up * compressed resources. This ensures the atomicity of the content * being compressed. As such, the cost of doing this is low as once * the resource is in the cache, the lookup won't be performed again * until the cache is cleared. That said, it's not a good idea * to have caching disabled in a production environment if leveraging * compression. * * If the resource isn't compressable, then we don't worry about creating * a few extra copies of ResourceInfo until the cache is populated. * </p> * * @param libraryName the name of the library (if any) * @param resourceName the name of the resource * @param contentType the content type of the resource. This will be * used to determine if the resource is compressable * @param ctx the {@link javax.faces.context.FacesContext} for the current * request * * @return a {@link ResourceInfo} if a resource if found matching the * provided arguments, otherwise, return <code>null</code> */ public ResourceInfo findResource(String libraryName, String resourceName, String contentType, FacesContext ctx) { return findResource(libraryName, resourceName, contentType, false, ctx); } public ResourceInfo findViewResource(String resourceName, String contentType, FacesContext facesContext) { String localePrefix = getLocalePrefix(facesContext); List<String> contracts = getResourceLibraryContracts(facesContext); ResourceInfo info = getFromCache(resourceName, null, localePrefix, contracts); if (info == null) { if (isCompressable(contentType, facesContext)) { info = findResourceCompressed(null, resourceName, true, localePrefix, contracts, facesContext); } else { info = findResourceNonCompressed(null, resourceName, true, localePrefix, contracts, facesContext); } } return info; } public ResourceInfo findResource(String libraryName, String resourceName, String contentType, boolean isViewResource, FacesContext ctx) { String localePrefix = getLocalePrefix(ctx); List<String> contracts = getResourceLibraryContracts(ctx); ResourceInfo info = getFromCache(resourceName, libraryName, localePrefix, contracts); if (info == null) { if (isCompressable(contentType, ctx)) { info = findResourceCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); } else { info = findResourceNonCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); } } return info; } public Stream<String> getViewResources(FacesContext facesContext, String path, int maxDepth, ResourceVisitOption... options) { return faceletWebappResourceHelper.getViewResources(facesContext, path, maxDepth, options); } // ----------------------------------------------------- Private Methods private ResourceInfo findResourceCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List<String> contracts, FacesContext ctx) { ResourceInfo info = null; lock.lock(); try { info = getFromCache(resourceName, libraryName, localePrefix, contracts); if (info == null) { info = doLookup(libraryName, resourceName, localePrefix, true, isViewResource, contracts, ctx); if (info != null) { addToCache(info, contracts); } } } finally { lock.unlock(); } return info; } private ResourceInfo findResourceNonCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List<String> contracts, FacesContext ctx) { ResourceInfo info = doLookup(libraryName, resourceName, localePrefix, false, isViewResource, contracts, ctx); if (info == null && contracts != null) { info = doLookup(libraryNameFromContracts(libraryName, contracts), resourceName, localePrefix, false, isViewResource, contracts, ctx); } if (info != null && !info.isDoNotCache()) { addToCache(info, contracts); } return info; } private String libraryNameFromContracts(String libraryName, List<String> contracts) { // If the library name is equal to one of the contracts, // assume the resource to be found is within that contract for (String contract : contracts) { if (contract.equals(libraryName)) { return null; } } return libraryName; } /** * Attempt to look up the Resource based on the provided details. * * @param libraryName the name of the library (if any) * @param resourceName the name of the resource * @param localePrefix the locale prefix for this resource (if any) * @param compressable if this resource can be compressed * @param isViewResource * @param contracts the contracts to consider * @param ctx the {@link javax.faces.context.FacesContext} for the current * request * * @return a {@link ResourceInfo} if a resource if found matching the * provided arguments, otherwise, return <code>null</code> */ private ResourceInfo doLookup(String libraryName, String resourceName, String localePrefix, boolean compressable, boolean isViewResource, List<String> contracts, FacesContext ctx) { // Loop over the contracts as described in deriveResourceIdConsideringLocalePrefixAndContracts in the spec for (String contract : contracts) { ResourceInfo info = getResourceInfo(libraryName, resourceName, localePrefix, contract, compressable, isViewResource, ctx, null); if (info != null) { return info; } } return getResourceInfo(libraryName, resourceName, localePrefix, null, compressable, isViewResource, ctx, null); } private ResourceInfo getResourceInfo(String libraryName, String resourceName, String localePrefix, String contract, boolean compressable, boolean isViewResource, FacesContext ctx, LibraryInfo library) { if (libraryName != null && !nameContainsForbiddenSequence(libraryName)) { library = findLibrary(libraryName, localePrefix, contract, ctx); if (library == null && localePrefix != null) { // no localized library found. Try to find a library that isn't localized. library = findLibrary(libraryName, null, contract, ctx); } if (library == null) { // If we don't have one by now, perhaps it's time to consider scanning directories. library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, false); if (library == null && localePrefix != null) { // no localized library found. Try to find // a library that isn't localized. library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, null, contract, ctx, false); } if (library == null) { return null; } } } else if (nameContainsForbiddenSequence(libraryName)) { return null; } String resName = trimLeadingSlash(resourceName); if (nameContainsForbiddenSequence(resName) || (!isViewResource && resName.startsWith("WEB-INF"))) { return null; } ResourceInfo info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); if (info == null && localePrefix != null) { // no localized resource found, try to find a // resource that isn't localized info = findResource(library, resourceName, null, compressable, isViewResource, ctx); } // If no resource has been found so far, and we have a library that // was found in the webapp filesystem, see if there is a matching // library on the classpath. If one is found, try to find a matching // resource in that library. if (info == null && library != null && library.getHelper() instanceof WebappResourceHelper) { LibraryInfo altLibrary = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); if (altLibrary != null) { VersionInfo originalVersion = library.getVersion(); VersionInfo altVersion = altLibrary.getVersion(); if (originalVersion == null && altVersion == null) { library = altLibrary; } else if (originalVersion == null && altVersion != null) { library = null; } else if (originalVersion != null && altVersion == null) { library = null; } else if (originalVersion.compareTo(altVersion) == 0) { library = altLibrary; } } if (library != null) { info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); if (info == null && localePrefix != null) { // no localized resource found, try to find a // resource that isn't localized info = findResource(library, resourceName, null, compressable, isViewResource, ctx); } } } return info; } /** * @param s input String * @return the String without a leading slash if it has one. */ private String trimLeadingSlash(String s) { if (s.charAt(0) == '/') { return s.substring(1); } else { return s; } } private static boolean nameContainsForbiddenSequence(String name) { boolean result = false; if (name != null) { name = name.toLowerCase(); result = name.startsWith(".") || name.contains("../") || name.contains("..\\") || name.startsWith("/") || name.startsWith("\\") || name.endsWith("/") || name.contains("..%2f") || name.contains("..%5c") || name.startsWith("%2f") || name.startsWith("%5c") || name.endsWith("%2f") || name.contains("..\\u002f") || name.contains("..\\u005c") || name.startsWith("\\u002f") || name.startsWith("\\u005c") || name.endsWith("\\u002f") ; } return result; } /** * * @param name the resource name * @param library the library name * @param localePrefix the Locale prefix * @param contracts * @return the {@link ResourceInfo} from the cache or <code>null</code> * if no cached entry is found */ private ResourceInfo getFromCache(String name, String library, String localePrefix, List<String> contracts) { if (cache == null) { return null; } return cache.get(name, library, localePrefix, contracts); } /** * Adds the the specified {@link ResourceInfo} to the cache. * @param info the @{link ResourceInfo} to add. * @param contracts the contracts */ private void addToCache(ResourceInfo info, List<String> contracts) { if (cache == null) { return; } cache.add(info, contracts); } /** * <p> Attempt to lookup and return a {@link LibraryInfo} based on the * specified <code>arguments</code>. * <p/> * <p> The lookup process will first search the file system of the web * application *within the resources directory*. * If the library is not found, then it processed to * searching the classpath, if not found there, search from the webapp root * *excluding* the resources directory.</p> * <p/> * <p> If a library is found, this method will return a {@link * LibraryInfo} instance that contains the name, version, and {@link * ResourceHelper}.</p> * * * @param libraryName the library to find * @param localePrefix the prefix for the desired locale * @param contract the contract to use *@param ctx the {@link javax.faces.context.FacesContext} for the current request * @return the Library instance for the specified library */ LibraryInfo findLibrary(String libraryName, String localePrefix, String contract, FacesContext ctx) { LibraryInfo library = webappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); if (library == null) { library = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); } if (library == null && contract == null) { // FCAPUTO facelets in contracts should have been found by the webapphelper already library = faceletWebappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); } // if not library is found at this point, let the caller deal with it return library; } LibraryInfo findLibraryOnClasspathWithZipDirectoryEntryScan(String libraryName, String localePrefix, String contract, FacesContext ctx, boolean forceScan) { return classpathResourceHelper.findLibraryWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, forceScan); } /** * <p> Attempt to lookup and return a {@link ResourceInfo} based on the * specified <code>arguments</code>. * <p/> * <p> The lookup process will first search the file system of the web * application. If the library is not found, then it processed to * searching the classpath.</p> * <p/> * <p> If a library is found, this method will return a {@link * LibraryInfo} instance that contains the name, version, and {@link * ResourceHelper}.</p> * * @param library the library the resource should be found in * @param resourceName the name of the resource * @param localePrefix the prefix for the desired locale * @param compressable <code>true</code> if the resource can be compressed * @param ctx the {@link javax.faces.context.FacesContext} for the current request * * @return the Library instance for the specified library */ private ResourceInfo findResource(LibraryInfo library, String resourceName, String localePrefix, boolean compressable, boolean skipToFaceletResourceHelper, FacesContext ctx) { if (library != null) { return library.getHelper().findResource(library, resourceName, localePrefix, compressable, ctx); } else { ResourceInfo resource = null; if (!skipToFaceletResourceHelper) { resource = webappResourceHelper.findResource(null, resourceName, localePrefix, compressable, ctx); } if (resource == null && !skipToFaceletResourceHelper) { resource = classpathResourceHelper.findResource(null, resourceName, localePrefix, compressable, ctx); } if (resource == null) { resource = faceletWebappResourceHelper.findResource(library, resourceName, localePrefix, compressable, ctx); } return resource; } } ResourceInfo findResource(String resourceId) { // PENDING(fcaputo) do we need to handle contracts here? String libraryName = null; String resourceName = null; int end = 0, start = 0; if (-1 != (end = resourceId.lastIndexOf("/"))) { resourceName = resourceId.substring(end+1); if (-1 != (start = resourceId.lastIndexOf("/", end - 1))) { libraryName = resourceId.substring(start+1, end); } else { libraryName = resourceId.substring(0, end); } } FacesContext context = FacesContext.getCurrentInstance(); LibraryInfo info = this.findLibrary(libraryName, null, null, context); ResourceInfo resourceInfo = this.findResource(info, resourceName, libraryName, true, false, context); return resourceInfo; } /** * <p> * Obtains the application configured message resources for the current * request locale. If a ResourceBundle is found and contains the key * <code>javax.faces.resource.localePrefix</code>, use the value associated * with that key as the prefix for locale specific resources. * </p> * * <p> * For example, say the request locale is en_US, and * <code>javax.faces.resourceLocalePrefix</code> is found with a value of * <code>en</code>, a resource path within a web application might look like * <code>/resources/en/corp/images/greetings.jpg</code> * </p> * * @param context the {@link FacesContext} for the current request * @return the localePrefix based on the current request, or <code>null</code> * if no prefix can be determined */ private String getLocalePrefix(FacesContext context) { String localePrefix = null; localePrefix = context.getExternalContext().getRequestParameterMap().get("loc"); if(localePrefix != null){ return localePrefix; } String appBundleName = context.getApplication().getMessageBundle(); if (null != appBundleName) { Locale locale = null; if (context.getViewRoot() != null) { locale = context.getViewRoot().getLocale(); } else { locale = context.getApplication().getViewHandler().calculateLocale(context); } try { ResourceBundle appBundle = ResourceBundle.getBundle(appBundleName, locale, Util.getCurrentLoader(ResourceManager.class)); localePrefix = appBundle .getString(ResourceHandler.LOCALE_PREFIX); } catch (MissingResourceException mre) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Ignoring missing resource", mre); } } } return localePrefix; } private List<String> getResourceLibraryContracts(FacesContext context) { UIViewRoot viewRoot = context.getViewRoot(); if(viewRoot == null) { if(context.getApplication().getResourceHandler().isResourceRequest(context)) { // it is a resource request. look at the parameter con=. String param = context.getExternalContext().getRequestParameterMap().get("con"); if(!nameContainsForbiddenSequence(param) && param != null && param.trim().length() > 0) { return Arrays.asList(param); } } // PENDING(edburns): calculate the contracts! return Collections.emptyList(); } return context.getResourceLibraryContracts(); } /** * @param contentType content-type in question * @param ctx the @{link FacesContext} for the current request * @return <code>true</code> if this resource can be compressed, otherwise * <code>false</code> */ private boolean isCompressable(String contentType, FacesContext ctx) { // No compression when developing. if (contentType == null || ctx.isProjectStage(ProjectStage.Development)) { return false; } else { if (compressableTypes != null && !compressableTypes.isEmpty()) { for (Pattern p : compressableTypes) { boolean matches = p.matcher(contentType).matches(); if (matches) { return true; } } } } return false; } /** * Init <code>compressableTypes</code> from the configuration. */ private void initCompressableTypes(Map<String, Object> appMap) { WebConfiguration config = WebConfiguration.getInstance(); String value = config.getOptionValue(WebConfiguration.WebContextInitParameter.CompressableMimeTypes); if (value != null && value.length() > 0) { String[] values = Util.split(appMap, value, ","); if (values != null) { for (String s : values) { String pattern = s.trim(); if (!isPatternValid(pattern)) { continue; } if (pattern.endsWith("/*")) { pattern = pattern.substring(0, pattern.indexOf("/*")); pattern += "/[a-z0-9.-]*"; } if (compressableTypes == null) { compressableTypes = new ArrayList<>(values.length); } try { compressableTypes.add(Pattern.compile(pattern)); } catch (PatternSyntaxException pse) { if (LOGGER.isLoggable(Level.WARNING)) { // PENDING i18n LOGGER.log(Level.WARNING, "jsf.resource.mime.type.configration.invalid", new Object[] { pattern, pse.getPattern()}); } } } } } } /** * @param input input mime-type pattern from the configuration * @return <code>true</code> if the input matches the expected pattern, * otherwise <code>false</code> */ private boolean isPatternValid(String input) { return (CONFIG_MIMETYPE_PATTERN.matcher(input).matches()); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_256_1
crossvul-java_data_bad_689_0
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } private static boolean doesNotContainFileColon(String path) { return !path.contains("file:"); } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @return if exists. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @return the input stream. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @return the url. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @return the resource. * @see spark.utils.StringUtils#applyRelativePath(String, String) */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @return the file name. * @see spark.utils.StringUtils#getFilename(String) */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_689_0
crossvul-java_data_bad_4612_2
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby.handlers; import com.google.common.base.Strings; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import static java.util.Objects.requireNonNull; import org.jooby.Asset; import org.jooby.Err; import org.jooby.Jooby; import org.jooby.MediaType; import org.jooby.Request; import org.jooby.Response; import org.jooby.Route; import org.jooby.Status; import org.jooby.funzy.Throwing; import org.jooby.funzy.Try; import org.jooby.internal.URLAsset; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.time.Duration; import java.util.Date; import java.util.Map; /** * Serve static resources, via {@link Jooby#assets(String)} or variants. * * <h1>e-tag support</h1> * <p> * It generates <code>ETag</code> headers using {@link Asset#etag()}. It handles * <code>If-None-Match</code> header automatically. * </p> * <p> * <code>ETag</code> handling is enabled by default. If you want to disabled etag support * {@link #etag(boolean)}. * </p> * * <h1>modified since support</h1> * <p> * It generates <code>Last-Modified</code> header using {@link Asset#lastModified()}. It handles * <code>If-Modified-Since</code> header automatically. * </p> * * <h1>CDN support</h1> * <p> * Asset can be serve from a content delivery network (a.k.a cdn). All you have to do is to set the * <code>assets.cdn</code> property. * </p> * * <pre> * assets.cdn = "http://d7471vfo50fqt.cloudfront.net" * </pre> * * <p> * Resolved assets are redirected to the cdn. * </p> * * @author edgar * @since 0.1.0 */ public class AssetHandler implements Route.Handler { private interface Loader { URL getResource(String name); } private static final Throwing.Function<String, String> prefix = prefix().memoized(); private Throwing.Function2<Request, String, String> fn; private Loader loader; private String cdn; private boolean etag = true; private long maxAge = -1; private boolean lastModified = true; private int statusCode = 404; /** * <p> * Creates a new {@link AssetHandler}. The handler accepts a location pattern, that serve for * locating the static resource. * </p> * * Given <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param pattern Pattern to locate static resources. * @param loader The one who load the static resources. */ public AssetHandler(final String pattern, final ClassLoader loader) { init(Route.normalize(pattern), Paths.get("public"), loader); } /** * <p> * Creates a new {@link AssetHandler}. The handler accepts a location pattern, that serve for * locating the static resource. * </p> * * Given <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param basedir Base directory. */ public AssetHandler(final Path basedir) { init("/{0}", basedir, getClass().getClassLoader()); } /** * <p> * Creates a new {@link AssetHandler}. The location pattern can be one of. * </p> * * Given <code>/</code> like in <code>assets("/assets/**", "/")</code> with: * * <pre> * GET /assets/js/index.js it translates the path to: /assets/js/index.js * </pre> * * Given <code>/assets</code> like in <code>assets("/js/**", "/assets")</code> with: * * <pre> * GET /js/index.js it translate the path to: /assets/js/index.js * </pre> * * Given <code>/META-INF/resources/webjars/{0}</code> like in * <code>assets("/webjars/**", "/META-INF/resources/webjars/{0}")</code> with: * * <pre> * GET /webjars/jquery/2.1.3/jquery.js it translate the path to: /META-INF/resources/webjars/jquery/2.1.3/jquery.js * </pre> * * @param pattern Pattern to locate static resources. */ public AssetHandler(final String pattern) { init(Route.normalize(pattern), Paths.get("public"), getClass().getClassLoader()); } /** * @param etag Turn on/off etag support. * @return This handler. */ public AssetHandler etag(final boolean etag) { this.etag = etag; return this; } /** * @param enabled Turn on/off last modified support. * @return This handler. */ public AssetHandler lastModified(final boolean enabled) { this.lastModified = enabled; return this; } /** * @param cdn If set, every resolved asset will be serve from it. * @return This handler. */ public AssetHandler cdn(final String cdn) { this.cdn = Strings.emptyToNull(cdn); return this; } /** * @param maxAge Set the cache header max-age value. * @return This handler. */ public AssetHandler maxAge(final Duration maxAge) { return maxAge(maxAge.getSeconds()); } /** * @param maxAge Set the cache header max-age value in seconds. * @return This handler. */ public AssetHandler maxAge(final long maxAge) { this.maxAge = maxAge; return this; } /** * Parse value as {@link Duration}. If the value is already a number then it uses as seconds. * Otherwise, it parse expressions like: 8m, 1h, 365d, etc... * * @param maxAge Set the cache header max-age value in seconds. * @return This handler. */ public AssetHandler maxAge(final String maxAge) { Try.apply(() -> Long.parseLong(maxAge)) .recover(x -> ConfigFactory.empty() .withValue("v", ConfigValueFactory.fromAnyRef(maxAge)) .getDuration("v") .getSeconds()) .onSuccess(this::maxAge); return this; } /** * Indicates what to do when an asset is missing (not resolved). Default action is to resolve them * as <code>404 (NOT FOUND)</code> request. * * If you specify a status code &lt;= 0, missing assets are ignored and the next handler on pipeline * will be executed. * * @param statusCode HTTP code or 0. * @return This handler. */ public AssetHandler onMissing(final int statusCode) { this.statusCode = statusCode; return this; } @Override public void handle(final Request req, final Response rsp) throws Throwable { String path = req.path(); URL resource = resolve(req, path); if (resource != null) { String localpath = resource.getPath(); int jarEntry = localpath.indexOf("!/"); if (jarEntry > 0) { localpath = localpath.substring(jarEntry + 2); } URLAsset asset = new URLAsset(resource, path, MediaType.byPath(localpath).orElse(MediaType.octetstream)); if (asset.exists()) { // cdn? if (cdn != null) { String absUrl = cdn + path; rsp.redirect(absUrl); rsp.end(); } else { doHandle(req, rsp, asset); } } } else if (statusCode > 0) { throw new Err(statusCode); } } private void doHandle(final Request req, final Response rsp, final Asset asset) throws Throwable { // handle etag if (this.etag) { String etag = asset.etag(); boolean ifnm = req.header("If-None-Match").toOptional() .map(etag::equals) .orElse(false); if (ifnm) { rsp.header("ETag", etag).status(Status.NOT_MODIFIED).end(); return; } rsp.header("ETag", etag); } // Handle if modified since if (this.lastModified) { long lastModified = asset.lastModified(); if (lastModified > 0) { boolean ifm = req.header("If-Modified-Since").toOptional(Long.class) .map(ifModified -> lastModified / 1000 <= ifModified / 1000) .orElse(false); if (ifm) { rsp.status(Status.NOT_MODIFIED).end(); return; } rsp.header("Last-Modified", new Date(lastModified)); } } // cache max-age if (maxAge > 0) { rsp.header("Cache-Control", "max-age=" + maxAge); } send(req, rsp, asset); } /** * Send an asset to the client. * * @param req Request. * @param rsp Response. * @param asset Resolve asset. * @throws Exception If send fails. */ protected void send(final Request req, final Response rsp, final Asset asset) throws Throwable { rsp.send(asset); } private URL resolve(final Request req, final String path) throws Throwable { String target = fn.apply(req, path); return resolve(target); } /** * Resolve a path as a {@link URL}. * * @param path Path of resource to resolve. * @return A URL or <code>null</code> for unresolved resource. * @throws Exception If something goes wrong. */ protected URL resolve(final String path) throws Exception { return loader.getResource(path); } private void init(final String pattern, final Path basedir, final ClassLoader loader) { requireNonNull(loader, "Resource loader is required."); this.fn = pattern.equals("/") ? (req, p) -> prefix.apply(p) : (req, p) -> MessageFormat.format(prefix.apply(pattern), vars(req)); this.loader = loader(basedir, loader); } private static Object[] vars(final Request req) { Map<Object, String> vars = req.route().vars(); return vars.values().toArray(new Object[vars.size()]); } private static Loader loader(final Path basedir, final ClassLoader classloader) { if (Files.exists(basedir)) { return name -> { Path path = basedir.resolve(name).normalize(); if (Files.exists(path) && path.startsWith(basedir)) { try { return path.toUri().toURL(); } catch (MalformedURLException x) { // shh } } return classloader.getResource(name); }; } return classloader::getResource; } private static Throwing.Function<String, String> prefix() { return p -> p.substring(1); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_2
crossvul-java_data_bad_256_0
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.application.applicationimpl; import static com.sun.faces.application.ApplicationImpl.THIS_LIBRARY; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.DateTimeConverterUsesSystemTimezone; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.RegisterConverterPropertyEditors; import static com.sun.faces.util.Util.isEmpty; import static com.sun.faces.util.Util.loadClass; import static com.sun.faces.util.Util.notNull; import static com.sun.faces.util.Util.notNullNamedObject; import static java.beans.Introspector.getBeanInfo; import static java.beans.PropertyEditorManager.findEditor; import static java.text.MessageFormat.format; import static java.util.Collections.unmodifiableMap; import static java.util.logging.Level.FINE; import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; import static javax.faces.application.Resource.COMPONENT_RESOURCE_KEY; import static javax.faces.component.UIComponent.ATTRS_WITH_DECLARED_DEFAULT_VALUES; import static javax.faces.component.UIComponent.BEANINFO_KEY; import static javax.faces.component.UIComponent.COMPOSITE_COMPONENT_TYPE_KEY; import java.beans.BeanDescriptor; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.enterprise.inject.spi.BeanManager; import javax.faces.FacesException; import javax.faces.application.Application; import javax.faces.application.Resource; import javax.faces.component.UIComponent; import javax.faces.component.behavior.Behavior; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.DateTimeConverter; import javax.faces.el.ValueBinding; import javax.faces.render.RenderKit; import javax.faces.render.Renderer; import javax.faces.validator.Validator; import javax.faces.view.ViewDeclarationLanguage; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.application.ConverterPropertyEditorFactory; import com.sun.faces.application.ViewMemberInstanceFactoryMetadataMap; import com.sun.faces.cdi.CdiUtils; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.MessageUtils; import com.sun.faces.util.ReflectionUtils; import com.sun.faces.util.Util; public class InstanceFactory { // Log instance for this class private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger(); private static final String CONTEXT = "context"; private static final String COMPONENT_EXPRESSION = "componentExpression"; private static final String COMPONENT_TYPE = "componentType"; private static final String COMPONENT_CLASS = "componentClass"; private static final Map<String, Class<?>[]> STANDARD_CONV_ID_TO_TYPE_MAP = new HashMap<>(8, 1.0f); private static final Map<Class<?>, String> STANDARD_TYPE_TO_CONV_ID_MAP = new HashMap<>(16, 1.0f); static { STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Byte", new Class[] { Byte.TYPE, Byte.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Boolean", new Class[] { Boolean.TYPE, Boolean.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Character", new Class[] { Character.TYPE, Character.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Short", new Class[] { Short.TYPE, Short.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Integer", new Class[] { Integer.TYPE, Integer.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Long", new Class[] { Long.TYPE, Long.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Float", new Class[] { Float.TYPE, Float.class }); STANDARD_CONV_ID_TO_TYPE_MAP.put("javax.faces.Double", new Class[] { Double.TYPE, Double.class }); for (Map.Entry<String, Class<?>[]> entry : STANDARD_CONV_ID_TO_TYPE_MAP.entrySet()) { Class<?>[] types = entry.getValue(); String key = entry.getKey(); for (Class<?> clazz : types) { STANDARD_TYPE_TO_CONV_ID_MAP.put(clazz, key); } } } private final String[] STANDARD_BY_TYPE_CONVERTER_CLASSES = { "java.math.BigDecimal", "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Double", "java.lang.Float", "java.lang.Integer", "java.lang.Long", "java.lang.Short", "java.lang.Enum" }; private Map<Class<?>, Object> converterTypeMap; private boolean registerPropertyEditors; private boolean passDefaultTimeZone; private TimeZone systemTimeZone; private static final class ComponentResourceClassNotFound{} // // These four maps store store "identifier" | "class name" // mappings. // private ViewMemberInstanceFactoryMetadataMap<String, Object> componentMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> behaviorMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> converterIdMap; private ViewMemberInstanceFactoryMetadataMap<String, Object> validatorMap; private Set<String> defaultValidatorIds; private volatile Map<String, String> defaultValidatorInfo; private final ApplicationAssociate associate; private Version version; /** * Stores the bean manager. */ private BeanManager beanManager; public InstanceFactory(ApplicationAssociate applicationAssociate) { this.associate = applicationAssociate; version = new Version(); componentMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); converterIdMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); converterTypeMap = new ConcurrentHashMap<>(); validatorMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); defaultValidatorIds = new LinkedHashSet<>(); behaviorMap = new ViewMemberInstanceFactoryMetadataMap<>(new ConcurrentHashMap<>()); WebConfiguration webConfig = WebConfiguration.getInstance(FacesContext.getCurrentInstance().getExternalContext()); registerPropertyEditors = webConfig.isOptionEnabled(RegisterConverterPropertyEditors); passDefaultTimeZone = webConfig.isOptionEnabled(DateTimeConverterUsesSystemTimezone); if (passDefaultTimeZone) { systemTimeZone = TimeZone.getDefault(); } } /** * @see javax.faces.application.Application#addComponent(java.lang.String, java.lang.String) */ public void addComponent(String componentType, String componentClass) { notNull(COMPONENT_TYPE, componentType); notNull(COMPONENT_CLASS, componentClass); if (LOGGER.isLoggable(FINE) && componentMap.containsKey(componentType)) { LOGGER.log(FINE, "componentType {0} has already been registered. Replacing existing component class type {1} with {2}.", new Object[] { componentType, componentMap.get(componentType), componentClass }); } componentMap.put(componentType, componentClass); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("added component of type ''{0}'' and class ''{1}''", componentType, componentClass)); } } public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType) throws FacesException { notNull(COMPONENT_EXPRESSION, componentExpression); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(context, componentExpression, componentType, null, true); } public UIComponent createComponent(String componentType) throws FacesException { notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(FacesContext.getCurrentInstance(), componentType, null, true); } public UIComponent createComponent(FacesContext context, Resource componentResource, ExpressionFactory expressionFactory) throws FacesException { // RELEASE_PENDING (rlubke,driscoll) this method needs review. notNull(CONTEXT, context); notNull("componentResource", componentResource); UIComponent result = null; // Use the application defined in the FacesContext as we may be calling // overriden methods Application app = context.getApplication(); ViewDeclarationLanguage vdl = app.getViewHandler().getViewDeclarationLanguage(context, context.getViewRoot().getViewId()); BeanInfo componentMetadata = vdl.getComponentMetadata(context, componentResource); if (componentMetadata != null) { BeanDescriptor componentBeanDescriptor = componentMetadata.getBeanDescriptor(); // Step 1. See if the composite component author explicitly // gave a componentType as part of the composite component metadata ValueExpression valueExpression = (ValueExpression) componentBeanDescriptor.getValue(COMPOSITE_COMPONENT_TYPE_KEY); if (valueExpression != null) { String componentType = (String) valueExpression.getValue(context.getELContext()); if (!isEmpty(componentType)) { result = app.createComponent(componentType); } } } // Step 2. If that didn't work, if a script based resource can be // found for the scriptComponentResource, see if a component can be generated from it if (result == null) { Resource scriptComponentResource = vdl.getScriptComponentResource(context, componentResource); if (scriptComponentResource != null) { result = createComponentFromScriptResource(context, scriptComponentResource, componentResource); } } // Step 3. Use the libraryName of the resource as the java package // and use the resourceName as the class name. See // if a Java class can be loaded if (result == null) { String packageName = componentResource.getLibraryName(); String className = componentResource.getResourceName(); className = packageName + '.' + className.substring(0, className.lastIndexOf('.')); try { Class<?> clazz = (Class<?>) componentMap.get(className); if (clazz == null) { clazz = loadClass(className, this); } if (clazz != ComponentResourceClassNotFound.class) { if (!associate.isDevModeEnabled()) { componentMap.put(className, clazz); } result = (UIComponent) clazz.newInstance(); } } catch (ClassNotFoundException ex) { if (!associate.isDevModeEnabled()) { componentMap.put(className, ComponentResourceClassNotFound.class); } } catch (InstantiationException | IllegalAccessException | ClassCastException ie) { throw new FacesException(ie); } } // Step 4. Use javax.faces.NamingContainer as the component type if (result == null) { result = app.createComponent("javax.faces.NamingContainer"); } result.setRendererType("javax.faces.Composite"); Map<String, Object> attrs = result.getAttributes(); attrs.put(COMPONENT_RESOURCE_KEY, componentResource); attrs.put(BEANINFO_KEY, componentMetadata); associate.getAnnotationManager().applyComponentAnnotations(context, result); pushDeclaredDefaultValuesToAttributesMap(context, componentMetadata, attrs, result, expressionFactory); return result; } public UIComponent createComponent(FacesContext context, String componentType, String rendererType) { return createComponentApplyAnnotations(context, componentType, rendererType, true); } public UIComponent createComponent(ValueExpression componentExpression, FacesContext context, String componentType, String rendererType) { notNull(COMPONENT_EXPRESSION, componentExpression); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); return createComponentApplyAnnotations(context, componentExpression, componentType, rendererType, true); } public UIComponent createComponent(ValueBinding componentBinding, FacesContext context, String componentType) throws FacesException { notNull("componentBinding", componentBinding); notNull(CONTEXT, context); notNull(COMPONENT_TYPE, componentType); Object result; boolean createOne = false; try { result = componentBinding.getValue(context); if (result != null) { createOne = !(result instanceof UIComponent); } if (result == null || createOne) { result = createComponentApplyAnnotations(context, componentType, null, false); componentBinding.setValue(context, result); } } catch (Exception ex) { throw new FacesException(ex); } return (UIComponent) result; } /** * @see javax.faces.application.Application#getComponentTypes() */ public Iterator<String> getComponentTypes() { return componentMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addBehavior(String, String) */ public void addBehavior(String behaviorId, String behaviorClass) { notNull("behaviorId", behaviorId); notNull("behaviorClass", behaviorClass); if (LOGGER.isLoggable(FINE) && behaviorMap.containsKey(behaviorId)) { LOGGER.log(FINE, "behaviorId {0} has already been registered. Replacing existing behavior class type {1} with {2}.", new Object[] { behaviorId, behaviorMap.get(behaviorId), behaviorClass }); } behaviorMap.put(behaviorId, behaviorClass); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("added behavior of type ''{0}'' class ''{1}''", behaviorId, behaviorClass)); } } /** * @see javax.faces.application.Application#createBehavior(String) */ public Behavior createBehavior(String behaviorId) throws FacesException { notNull("behaviorId", behaviorId); Behavior behavior = createCDIBehavior(behaviorId); if (behavior != null) { return behavior; } behavior = newThing(behaviorId, behaviorMap); notNullNamedObject(behavior, behaviorId, "jsf.cannot_instantiate_behavior_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created behavior of type ''{0}''", behaviorId)); } associate.getAnnotationManager().applyBehaviorAnnotations(FacesContext.getCurrentInstance(), behavior); return behavior; } /** * @see javax.faces.application.Application#getBehaviorIds() */ public Iterator<String> getBehaviorIds() { return behaviorMap.keySet().iterator(); } public void addConverter(String converterId, String converterClass) { notNull("converterId", converterId); notNull("converterClass", converterClass); if (LOGGER.isLoggable(FINE) && converterIdMap.containsKey(converterId)) { LOGGER.log(FINE, "converterId {0} has already been registered. Replacing existing converter class type {1} with {2}.", new Object[] { converterId, converterIdMap.get(converterId), converterClass }); } converterIdMap.put(converterId, converterClass); Class<?>[] types = STANDARD_CONV_ID_TO_TYPE_MAP.get(converterId); if (types != null) { for (Class<?> clazz : types) { // go directly against map to prevent cyclic method calls converterTypeMap.put(clazz, converterClass); addPropertyEditorIfNecessary(clazz); } } if (LOGGER.isLoggable(FINE)) { LOGGER.fine(format("added converter of type ''{0}'' and class ''{1}''", converterId, converterClass)); } } /** * @see javax.faces.application.Application#addConverter(Class, String) */ public void addConverter(Class<?> targetClass, String converterClass) { notNull("targetClass", targetClass); notNull("converterClass", converterClass); String converterId = STANDARD_TYPE_TO_CONV_ID_MAP.get(targetClass); if (converterId != null) { addConverter(converterId, converterClass); } else { if (LOGGER.isLoggable(FINE) && converterTypeMap.containsKey(targetClass)) { LOGGER.log(FINE, "converter target class {0} has already been registered. Replacing existing converter class type {1} with {2}.", new Object[] { targetClass.getName(), converterTypeMap.get(targetClass), converterClass }); } converterTypeMap.put(targetClass, converterClass); addPropertyEditorIfNecessary(targetClass); } if (LOGGER.isLoggable(FINE)) { LOGGER.fine(format("added converter of class type ''{0}''", converterClass)); } } /** * @see javax.faces.application.Application#createConverter(String) */ public Converter<?> createConverter(String converterId) { notNull("converterId", converterId); Converter<?> converter = createCDIConverter(converterId); if (converter != null) { return converter; } converter = newThing(converterId, converterIdMap); notNullNamedObject(converter, converterId, "jsf.cannot_instantiate_converter_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created converter of type ''{0}''", converterId)); } if (passDefaultTimeZone && converter instanceof DateTimeConverter) { ((DateTimeConverter) converter).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), converter); return converter; } /** * @see javax.faces.application.Application#createConverter(Class) */ public Converter createConverter(Class<?> targetClass) { Util.notNull("targetClass", targetClass); Converter returnVal = null; if (version.isJsf23()) { BeanManager beanManager = getBeanManager(); returnVal = CdiUtils.createConverter(beanManager, targetClass); if (returnVal != null) { return returnVal; } } returnVal = (Converter) newConverter(targetClass, converterTypeMap, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } // Search for converters registered to interfaces implemented by // targetClass Class<?>[] interfaces = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { returnVal = createConverterBasedOnClass(interfaces[i], targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } } } // Search for converters registered to superclasses of targetClass Class<?> superclass = targetClass.getSuperclass(); if (superclass != null) { returnVal = createConverterBasedOnClass(superclass, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } if (passDefaultTimeZone && returnVal instanceof DateTimeConverter) { ((DateTimeConverter) returnVal).setTimeZone(systemTimeZone); } associate.getAnnotationManager().applyConverterAnnotations(FacesContext.getCurrentInstance(), returnVal); return returnVal; } } return returnVal; } /** * @see javax.faces.application.Application#getConverterIds() */ public Iterator<String> getConverterIds() { return converterIdMap.keySet().iterator(); } /** * @see javax.faces.application.Application#getConverterTypes() */ public Iterator<Class<?>> getConverterTypes() { return converterTypeMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addValidator(String, String) */ public void addValidator(String validatorId, String validatorClass) { Util.notNull("validatorId", validatorId); Util.notNull("validatorClass", validatorClass); if (LOGGER.isLoggable(Level.FINE) && validatorMap.containsKey(validatorId)) { LOGGER.log(Level.FINE, "validatorId {0} has already been registered. Replacing existing validator class type {1} with {2}.", new Object[] { validatorId, validatorMap.get(validatorId), validatorClass }); } validatorMap.put(validatorId, validatorClass); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("added validator of type ''{0}'' class ''{1}''", validatorId, validatorClass)); } } /** * @see javax.faces.application.Application#createValidator(String) */ public Validator<?> createValidator(String validatorId) throws FacesException { notNull("validatorId", validatorId); Validator<?> validator = createCDIValidator(validatorId); if (validator != null) { return validator; } validator = newThing(validatorId, validatorMap); notNullNamedObject(validator, validatorId, "jsf.cannot_instantiate_validator_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.fine(MessageFormat.format("created validator of type ''{0}''", validatorId)); } associate.getAnnotationManager().applyValidatorAnnotations(FacesContext.getCurrentInstance(), validator); return validator; } /** * @see javax.faces.application.Application#getValidatorIds() */ public Iterator<String> getValidatorIds() { return validatorMap.keySet().iterator(); } /** * @see javax.faces.application.Application#addDefaultValidatorId(String) */ public synchronized void addDefaultValidatorId(String validatorId) { notNull("validatorId", validatorId); defaultValidatorInfo = null; defaultValidatorIds.add(validatorId); } /** * @see javax.faces.application.Application#getDefaultValidatorInfo() */ public Map<String, String> getDefaultValidatorInfo() { if (defaultValidatorInfo == null) { synchronized (this) { if (defaultValidatorInfo == null) { defaultValidatorInfo = new LinkedHashMap<>(); if (!defaultValidatorIds.isEmpty()) { for (String id : defaultValidatorIds) { String validatorClass; Object result = validatorMap.get(id); if (null != result) { if (result instanceof Class) { validatorClass = ((Class) result).getName(); } else { validatorClass = result.toString(); } defaultValidatorInfo.put(id, validatorClass); } } } } } defaultValidatorInfo = unmodifiableMap(defaultValidatorInfo); } return defaultValidatorInfo; } // --------------------------------------------------------- Private Methods private UIComponent createComponentFromScriptResource(FacesContext context, Resource scriptComponentResource, Resource componentResource) { UIComponent result = null; String className = scriptComponentResource.getResourceName(); int lastDot = className.lastIndexOf('.'); className = className.substring(0, lastDot); try { Class<?> componentClass = (Class<?>) componentMap.get(className); if (componentClass == null) { componentClass = Util.loadClass(className, this); } if (!associate.isDevModeEnabled()) { componentMap.put(className, componentClass); } result = (UIComponent) componentClass.newInstance(); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, null, ex); } } if (result != null) { // Make sure the resource is there for the annotation processor. result.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, componentResource); // In case there are any "this" references, // make sure they can be resolved. context.getAttributes().put(THIS_LIBRARY, componentResource.getLibraryName()); try { associate.getAnnotationManager().applyComponentAnnotations(context, result); } finally { context.getAttributes().remove(THIS_LIBRARY); } } return result; } /** * Leveraged by * {@link Application#createComponent(javax.el.ValueExpression, javax.faces.context.FacesContext, String)} * and * {@link Application#createComponent(javax.el.ValueExpression, javax.faces.context.FacesContext, String, String)}. * This method will apply any component and render annotations that may be present. */ private UIComponent createComponentApplyAnnotations(FacesContext ctx, ValueExpression componentExpression, String componentType, String rendererType, boolean applyAnnotations) { UIComponent c; try { c = (UIComponent) componentExpression.getValue(ctx.getELContext()); if (c == null) { c = this.createComponentApplyAnnotations(ctx, componentType, rendererType, applyAnnotations); componentExpression.setValue(ctx.getELContext(), c); } else if (applyAnnotations) { this.applyAnnotations(ctx, rendererType, c); } } catch (Exception ex) { throw new FacesException(ex); } return c; } /** * Leveraged by {@link Application#createComponent(String)} and * {@link Application#createComponent(javax.faces.context.FacesContext, String, String)} This * method will apply any component and render annotations that may be present. */ private UIComponent createComponentApplyAnnotations(FacesContext ctx, String componentType, String rendererType, boolean applyAnnotations) { UIComponent component; try { component = newThing(componentType, componentMap); } catch (Exception ex) { if (LOGGER.isLoggable(SEVERE)) { LOGGER.log(Level.SEVERE, "jsf.cannot_instantiate_component_error", componentType); } throw new FacesException(ex); } notNullNamedObject(component, componentType, "jsf.cannot_instantiate_component_error"); if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, MessageFormat.format("Created component with component type of ''{0}''", componentType)); } if (applyAnnotations) { applyAnnotations(ctx, rendererType, component); } return component; } /** * Process any annotations associated with this component/renderer. */ private void applyAnnotations(FacesContext ctx, String rendererType, UIComponent c) { if (c != null && ctx != null) { associate.getAnnotationManager().applyComponentAnnotations(ctx, c); if (rendererType != null) { RenderKit rk = ctx.getRenderKit(); Renderer r = null; if (rk != null) { r = rk.getRenderer(c.getFamily(), rendererType); if (r != null) { c.setRendererType(rendererType); associate.getAnnotationManager().applyRendererAnnotations(ctx, r, c); } } if ((rk == null || r == null) && LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Unable to create Renderer with rendererType {0} for component with component type of {1}", new Object[] { rendererType, c.getFamily() }); } } } } /** * <p> * PRECONDITIONS: the values in the Map are either Strings representing fully qualified java * class names, or java.lang.Class instances. * </p> * <p> * ALGORITHM: Look in the argument map for a value for the argument key. If found, if the value * is instanceof String, assume the String specifies a fully qualified java class name and * obtain the java.lang.Class instance for that String using Util.loadClass(). Replace the * String instance in the argument map with the Class instance. If the value is instanceof * Class, proceed. Assert that the value is either instanceof java.lang.Class or * java.lang.String. * </p> * <p> * Now that you have a java.lang.class, call its newInstance and return it as the result of this * method. * </p> * * @param key Used to look up the value in the <code>Map</code>. * @param map The <code>Map</code> that will be searched. * @return The new object instance. */ @SuppressWarnings("unchecked") private <T> T newThing(String key, ViewMemberInstanceFactoryMetadataMap<String, Object> map) { Object result; Class<?> clazz; Object value; value = map.get(key); if (value == null) { return null; } assert value instanceof String || value instanceof Class; if (value instanceof String) { String cValue = (String) value; try { clazz = Util.loadClass(cValue, value); if (!associate.isDevModeEnabled()) { map.put(key, clazz); } assert clazz != null; } catch (Exception e) { throw new FacesException(e.getMessage(), e); } } else { clazz = (Class) value; } try { result = clazz.newInstance(); } catch (Throwable t) { Throwable previousT; do { previousT = t; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Unable to load class: ", t); } } while (null != (t = t.getCause())); t = previousT; throw new FacesException(MessageUtils.getExceptionMessageString(MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, clazz.getName()), t); } return (T) result; } /* * This method makes it so that any cc:attribute elements that have a "default" attribute value * have those values pushed into the composite component attribute map so that programmatic * access (as opposed to EL access) will find the attribute values. * */ @SuppressWarnings("unchecked") private void pushDeclaredDefaultValuesToAttributesMap(FacesContext context, BeanInfo componentMetadata, Map<String, Object> attrs, UIComponent component, ExpressionFactory expressionFactory) { Collection<String> attributesWithDeclaredDefaultValues = null; PropertyDescriptor[] propertyDescriptors = null; for (PropertyDescriptor propertyDescriptor : componentMetadata.getPropertyDescriptors()) { Object defaultValue = propertyDescriptor.getValue("default"); if (defaultValue != null) { String key = propertyDescriptor.getName(); boolean isLiteralText = false; if (defaultValue instanceof ValueExpression) { isLiteralText = ((ValueExpression) defaultValue).isLiteralText(); if (isLiteralText) { defaultValue = ((ValueExpression) defaultValue).getValue(context.getELContext()); } } // Ensure this attribute is not a method-signature. method-signature // declared default values are handled in retargetMethodExpressions. if (propertyDescriptor.getValue("method-signature") == null || propertyDescriptor.getValue("type") != null) { if (attributesWithDeclaredDefaultValues == null) { BeanDescriptor beanDescriptor = componentMetadata.getBeanDescriptor(); attributesWithDeclaredDefaultValues = (Collection<String>) beanDescriptor.getValue(ATTRS_WITH_DECLARED_DEFAULT_VALUES); if (attributesWithDeclaredDefaultValues == null) { attributesWithDeclaredDefaultValues = new HashSet<>(); beanDescriptor.setValue(ATTRS_WITH_DECLARED_DEFAULT_VALUES, attributesWithDeclaredDefaultValues); } } attributesWithDeclaredDefaultValues.add(key); // Only store the attribute if it is literal text. If it // is a ValueExpression, it will be handled explicitly in // CompositeComponentAttributesELResolver.ExpressionEvalMap.get(). // If it is a MethodExpression, it will be dealt with in // retargetMethodExpressions. if (isLiteralText) { try { if (propertyDescriptors == null) { propertyDescriptors = getBeanInfo(component.getClass()).getPropertyDescriptors(); } } catch (IntrospectionException e) { throw new FacesException(e); } defaultValue = convertValueToTypeIfNecessary(key, defaultValue, propertyDescriptors, expressionFactory); attrs.put(key, defaultValue); } } } } } /** * Helper method to convert a value to a type as defined in PropertyDescriptor(s) * * @param name * @param value * @param propertyDescriptors * @return value */ private Object convertValueToTypeIfNecessary(String name, Object value, PropertyDescriptor[] propertyDescriptors, ExpressionFactory expressionFactory) { for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(name)) { value = expressionFactory.coerceToType(value, propertyDescriptor.getPropertyType()); break; } } return value; } /** * <p> * To enable EL Coercion to use JSF Custom converters, this method will call * <code>PropertyEditorManager.registerEditor()</code>, passing the * <code>ConverterPropertyEditor</code> class for the <code>targetClass</code> if the target * class is not one of the standard by-type converter target classes. * * @param targetClass the target class for which a PropertyEditory may or may not be created */ private void addPropertyEditorIfNecessary(Class<?> targetClass) { if (!registerPropertyEditors) { return; } PropertyEditor editor = findEditor(targetClass); if (editor != null) { return; } String className = targetClass.getName(); // Don't add a PropertyEditor for the standard by-type converters. if (targetClass.isPrimitive()) { return; } for (String standardClass : STANDARD_BY_TYPE_CONVERTER_CLASSES) { if (standardClass.indexOf(className) != -1) { return; } } Class<?> editorClass = ConverterPropertyEditorFactory.getDefaultInstance().definePropertyEditorClassFor(targetClass); if (editorClass != null) { PropertyEditorManager.registerEditor(targetClass, editorClass); } else { if (LOGGER.isLoggable(WARNING)) { LOGGER.warning(MessageFormat.format("definePropertyEditorClassFor({0}) returned null.", targetClass.getName())); } } } private Converter createConverterBasedOnClass(Class<?> targetClass, Class<?> baseClass) { Converter returnVal = (Converter) newConverter(targetClass, converterTypeMap, baseClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } // Search for converters registered to interfaces implemented by // targetClass Class<?>[] interfaces = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { returnVal = createConverterBasedOnClass(interfaces[i], null); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } } } // Search for converters registered to superclasses of targetClass Class<?> superclass = targetClass.getSuperclass(); if (superclass != null) { returnVal = createConverterBasedOnClass(superclass, targetClass); if (returnVal != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(MessageFormat.format("Created converter of type ''{0}''", returnVal.getClass().getName())); } return returnVal; } } return returnVal; } /** * <p> * The same as newThing except that a single argument constructor that accepts a Class is looked * for before calling the no-arg version. * </p> * * <p> * PRECONDITIONS: the values in the Map are either Strings representing fully qualified java * class names, or java.lang.Class instances. * </p> * <p> * ALGORITHM: Look in the argument map for a value for the argument key. If found, if the value * is instanceof String, assume the String specifies a fully qualified java class name and * obtain the java.lang.Class instance for that String using Util.loadClass(). Replace the * String instance in the argument map with the Class instance. If the value is instanceof * Class, proceed. Assert that the value is either instanceof java.lang.Class or * java.lang.String. * </p> * <p> * Now that you have a java.lang.class, call its newInstance and return it as the result of this * method. * </p> * * @param key Used to look up the value in the <code>Map</code>. * @param map The <code>Map</code> that will be searched. * @param targetClass the target class for the single argument ctor * @return The new object instance. */ protected Object newConverter(Class<?> key, Map<Class<?>, Object> map, Class<?> targetClass) { assert key != null && map != null; Object result = null; Class<?> clazz; Object value; value = map.get(key); if (value == null) { return null; } assert value instanceof String || value instanceof Class; if (value instanceof String) { String cValue = (String) value; try { clazz = Util.loadClass(cValue, value); if (!associate.isDevModeEnabled()) { map.put(key, clazz); } assert clazz != null; } catch (Exception e) { throw new FacesException(e.getMessage(), e); } } else { clazz = (Class) value; } Constructor ctor = ReflectionUtils.lookupConstructor(clazz, Class.class); Throwable cause = null; if (ctor != null) { try { result = ctor.newInstance(targetClass); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { cause = e; } } else { try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { cause = e; } } if (null != cause) { throw new FacesException(MessageUtils.getExceptionMessageString(MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, clazz.getName()), cause); } return result; } /** * Get the bean manager. * * @return the bean manager. */ private BeanManager getBeanManager() { if (beanManager == null) { FacesContext facesContext = FacesContext.getCurrentInstance(); beanManager = Util.getCdiBeanManager(facesContext); } return beanManager; } private Behavior createCDIBehavior(String behaviorId) { if (version.isJsf23()) { return CdiUtils.createBehavior(getBeanManager(), behaviorId); } return null; } private Converter<?> createCDIConverter(String converterId) { if (version.isJsf23()) { return CdiUtils.createConverter(getBeanManager(), converterId); } return null; } private Validator<?> createCDIValidator(String validatorId) { if (version.isJsf23()) { return CdiUtils.createValidator(getBeanManager(), validatorId); } return null; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_256_0
crossvul-java_data_good_498_2
package cc.mrbird.common.handler; import cc.mrbird.common.domain.ResponseBo; import cc.mrbird.common.exception.FileDownloadException; import cc.mrbird.common.exception.LimitAccessException; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.session.ExpiredSessionException; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice @Order(value = Ordered.HIGHEST_PRECEDENCE) public class GlobalExceptionHandler { @ExceptionHandler(value = AuthorizationException.class) public Object handleAuthorizationException(HttpServletRequest request) { if (isAjaxRequest(request)) { return ResponseBo.error("暂无权限,请联系管理员!"); } else { ModelAndView mav = new ModelAndView(); mav.setViewName("error/403"); return mav; } } @ExceptionHandler(value = ExpiredSessionException.class) public String handleExpiredSessionException() { return "login"; } @ExceptionHandler(value = LimitAccessException.class) public ResponseBo handleLimitAccessException(LimitAccessException e) { return ResponseBo.error(e.getMessage()); } @ExceptionHandler(value = FileDownloadException.class) public ResponseBo handleFileDownloadException(FileDownloadException e) { return ResponseBo.error(e.getMessage()); } private static boolean isAjaxRequest(HttpServletRequest request) { return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_498_2
crossvul-java_data_good_256_1
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.faces.application.resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Stream; import javax.faces.application.ProjectStage; import javax.faces.application.ResourceHandler; import javax.faces.application.ResourceVisitOption; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.Util; /** * This class is used to lookup {@link ResourceInfo} instances * and cache any that are successfully looked up to reduce the * computational overhead with the scanning/version checking. * * @since 2.0 */ public class ResourceManager { private static final Logger LOGGER = FacesLogger.RESOURCE.getLogger(); /** * {@link Pattern} for valid mime types to configure compression. */ private static final Pattern CONFIG_MIMETYPE_PATTERN = Pattern.compile("[a-z-]*/[a-z0-9.\\*-]*"); private FaceletWebappResourceHelper faceletWebappResourceHelper = new FaceletWebappResourceHelper(); /** * {@link ResourceHelper} used for looking up webapp-based resources. */ private ResourceHelper webappResourceHelper = new WebappResourceHelper(); /** * {@link ResourceHelper} used for looking up classpath-based resources. */ private ClasspathResourceHelper classpathResourceHelper = new ClasspathResourceHelper(); /** * Cache for storing {@link ResourceInfo} instances to reduce the cost * of the resource lookups. */ private ResourceCache cache; /** * Patterns used to find {@link ResourceInfo} instances that may have their * content compressed. */ private List<Pattern> compressableTypes; /** * This lock is used to ensure the lookup of compressable {@link ResourceInfo} * instances are atomic to prevent theading issues when writing the compressed * content during a lookup. */ private ReentrantLock lock = new ReentrantLock(); // ------------------------------------------------------------ Constructors /* * This ctor is only ever called by test code. */ public ResourceManager(ResourceCache cache) { this.cache = cache; Map<String, Object> throwAwayMap = new HashMap<>(); initCompressableTypes(throwAwayMap); } /** * Constructs a new <code>ResourceManager</code>. Note: if the current * {@link ProjectStage} is {@link ProjectStage#Development} caching or * {@link ResourceInfo} instances will not occur. */ public ResourceManager(Map<String, Object> appMap, ResourceCache cache) { this.cache = cache; initCompressableTypes(appMap); } // ------------------------------------------------------ Public Methods /** * <p> * Attempt to lookup a {@link ResourceInfo} based on the specified * <code>libraryName<code> and <code>resourceName</code> * </p> * * <p> * Implementation Note: Synchronization is necessary when looking up * compressed resources. This ensures the atomicity of the content * being compressed. As such, the cost of doing this is low as once * the resource is in the cache, the lookup won't be performed again * until the cache is cleared. That said, it's not a good idea * to have caching disabled in a production environment if leveraging * compression. * * If the resource isn't compressable, then we don't worry about creating * a few extra copies of ResourceInfo until the cache is populated. * </p> * * @param libraryName the name of the library (if any) * @param resourceName the name of the resource * @param contentType the content type of the resource. This will be * used to determine if the resource is compressable * @param ctx the {@link javax.faces.context.FacesContext} for the current * request * * @return a {@link ResourceInfo} if a resource if found matching the * provided arguments, otherwise, return <code>null</code> */ public ResourceInfo findResource(String libraryName, String resourceName, String contentType, FacesContext ctx) { return findResource(libraryName, resourceName, contentType, false, ctx); } public ResourceInfo findViewResource(String resourceName, String contentType, FacesContext facesContext) { String localePrefix = getLocalePrefix(facesContext); List<String> contracts = getResourceLibraryContracts(facesContext); ResourceInfo info = getFromCache(resourceName, null, localePrefix, contracts); if (info == null) { if (isCompressable(contentType, facesContext)) { info = findResourceCompressed(null, resourceName, true, localePrefix, contracts, facesContext); } else { info = findResourceNonCompressed(null, resourceName, true, localePrefix, contracts, facesContext); } } return info; } public ResourceInfo findResource(String libraryName, String resourceName, String contentType, boolean isViewResource, FacesContext ctx) { String localePrefix = getLocalePrefix(ctx); List<String> contracts = getResourceLibraryContracts(ctx); ResourceInfo info = getFromCache(resourceName, libraryName, localePrefix, contracts); if (info == null) { if (isCompressable(contentType, ctx)) { info = findResourceCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); } else { info = findResourceNonCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); } } return info; } public Stream<String> getViewResources(FacesContext facesContext, String path, int maxDepth, ResourceVisitOption... options) { return faceletWebappResourceHelper.getViewResources(facesContext, path, maxDepth, options); } // ----------------------------------------------------- Private Methods private ResourceInfo findResourceCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List<String> contracts, FacesContext ctx) { ResourceInfo info = null; lock.lock(); try { info = getFromCache(resourceName, libraryName, localePrefix, contracts); if (info == null) { info = doLookup(libraryName, resourceName, localePrefix, true, isViewResource, contracts, ctx); if (info != null) { addToCache(info, contracts); } } } finally { lock.unlock(); } return info; } private ResourceInfo findResourceNonCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List<String> contracts, FacesContext ctx) { ResourceInfo info = doLookup(libraryName, resourceName, localePrefix, false, isViewResource, contracts, ctx); if (info == null && contracts != null) { info = doLookup(libraryNameFromContracts(libraryName, contracts), resourceName, localePrefix, false, isViewResource, contracts, ctx); } if (info != null && !info.isDoNotCache()) { addToCache(info, contracts); } return info; } private String libraryNameFromContracts(String libraryName, List<String> contracts) { // If the library name is equal to one of the contracts, // assume the resource to be found is within that contract for (String contract : contracts) { if (contract.equals(libraryName)) { return null; } } return libraryName; } /** * Attempt to look up the Resource based on the provided details. * * @param libraryName the name of the library (if any) * @param resourceName the name of the resource * @param localePrefix the locale prefix for this resource (if any) * @param compressable if this resource can be compressed * @param isViewResource * @param contracts the contracts to consider * @param ctx the {@link javax.faces.context.FacesContext} for the current * request * * @return a {@link ResourceInfo} if a resource if found matching the * provided arguments, otherwise, return <code>null</code> */ private ResourceInfo doLookup(String libraryName, String resourceName, String localePrefix, boolean compressable, boolean isViewResource, List<String> contracts, FacesContext ctx) { // Loop over the contracts as described in deriveResourceIdConsideringLocalePrefixAndContracts in the spec for (String contract : contracts) { ResourceInfo info = getResourceInfo(libraryName, resourceName, localePrefix, contract, compressable, isViewResource, ctx, null); if (info != null) { return info; } } return getResourceInfo(libraryName, resourceName, localePrefix, null, compressable, isViewResource, ctx, null); } private ResourceInfo getResourceInfo(String libraryName, String resourceName, String localePrefix, String contract, boolean compressable, boolean isViewResource, FacesContext ctx, LibraryInfo library) { if (libraryName != null && !nameContainsForbiddenSequence(libraryName)) { library = findLibrary(libraryName, localePrefix, contract, ctx); if (library == null && localePrefix != null) { // no localized library found. Try to find a library that isn't localized. library = findLibrary(libraryName, null, contract, ctx); } if (library == null) { // If we don't have one by now, perhaps it's time to consider scanning directories. library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, false); if (library == null && localePrefix != null) { // no localized library found. Try to find // a library that isn't localized. library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, null, contract, ctx, false); } if (library == null) { return null; } } } else if (nameContainsForbiddenSequence(libraryName)) { return null; } String resName = trimLeadingSlash(resourceName); if (nameContainsForbiddenSequence(resName) || (!isViewResource && resName.startsWith("WEB-INF"))) { return null; } ResourceInfo info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); if (info == null && localePrefix != null) { // no localized resource found, try to find a // resource that isn't localized info = findResource(library, resourceName, null, compressable, isViewResource, ctx); } // If no resource has been found so far, and we have a library that // was found in the webapp filesystem, see if there is a matching // library on the classpath. If one is found, try to find a matching // resource in that library. if (info == null && library != null && library.getHelper() instanceof WebappResourceHelper) { LibraryInfo altLibrary = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); if (altLibrary != null) { VersionInfo originalVersion = library.getVersion(); VersionInfo altVersion = altLibrary.getVersion(); if (originalVersion == null && altVersion == null) { library = altLibrary; } else if (originalVersion == null && altVersion != null) { library = null; } else if (originalVersion != null && altVersion == null) { library = null; } else if (originalVersion.compareTo(altVersion) == 0) { library = altLibrary; } } if (library != null) { info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); if (info == null && localePrefix != null) { // no localized resource found, try to find a // resource that isn't localized info = findResource(library, resourceName, null, compressable, isViewResource, ctx); } } } return info; } /** * @param s input String * @return the String without a leading slash if it has one. */ private String trimLeadingSlash(String s) { if (s.charAt(0) == '/') { return s.substring(1); } else { return s; } } private static boolean nameContainsForbiddenSequence(String name) { boolean result = false; if (name != null) { name = name.toLowerCase(); result = name.startsWith(".") || name.contains("../") || name.contains("..\\") || name.startsWith("/") || name.startsWith("\\") || name.endsWith("/") || name.contains("..%2f") || name.contains("..%5c") || name.startsWith("%2f") || name.startsWith("%5c") || name.endsWith("%2f") || name.contains("..\\u002f") || name.contains("..\\u005c") || name.startsWith("\\u002f") || name.startsWith("\\u005c") || name.endsWith("\\u002f") ; } return result; } /** * * @param name the resource name * @param library the library name * @param localePrefix the Locale prefix * @param contracts * @return the {@link ResourceInfo} from the cache or <code>null</code> * if no cached entry is found */ private ResourceInfo getFromCache(String name, String library, String localePrefix, List<String> contracts) { if (cache == null) { return null; } return cache.get(name, library, localePrefix, contracts); } /** * Adds the the specified {@link ResourceInfo} to the cache. * @param info the @{link ResourceInfo} to add. * @param contracts the contracts */ private void addToCache(ResourceInfo info, List<String> contracts) { if (cache == null) { return; } cache.add(info, contracts); } /** * <p> Attempt to lookup and return a {@link LibraryInfo} based on the * specified <code>arguments</code>. * <p/> * <p> The lookup process will first search the file system of the web * application *within the resources directory*. * If the library is not found, then it processed to * searching the classpath, if not found there, search from the webapp root * *excluding* the resources directory.</p> * <p/> * <p> If a library is found, this method will return a {@link * LibraryInfo} instance that contains the name, version, and {@link * ResourceHelper}.</p> * * * @param libraryName the library to find * @param localePrefix the prefix for the desired locale * @param contract the contract to use *@param ctx the {@link javax.faces.context.FacesContext} for the current request * @return the Library instance for the specified library */ LibraryInfo findLibrary(String libraryName, String localePrefix, String contract, FacesContext ctx) { LibraryInfo library = webappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); if (library == null) { library = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); } if (library == null && contract == null) { // FCAPUTO facelets in contracts should have been found by the webapphelper already library = faceletWebappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); } // if not library is found at this point, let the caller deal with it return library; } LibraryInfo findLibraryOnClasspathWithZipDirectoryEntryScan(String libraryName, String localePrefix, String contract, FacesContext ctx, boolean forceScan) { return classpathResourceHelper.findLibraryWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, forceScan); } /** * <p> Attempt to lookup and return a {@link ResourceInfo} based on the * specified <code>arguments</code>. * <p/> * <p> The lookup process will first search the file system of the web * application. If the library is not found, then it processed to * searching the classpath.</p> * <p/> * <p> If a library is found, this method will return a {@link * LibraryInfo} instance that contains the name, version, and {@link * ResourceHelper}.</p> * * @param library the library the resource should be found in * @param resourceName the name of the resource * @param localePrefix the prefix for the desired locale * @param compressable <code>true</code> if the resource can be compressed * @param ctx the {@link javax.faces.context.FacesContext} for the current request * * @return the Library instance for the specified library */ private ResourceInfo findResource(LibraryInfo library, String resourceName, String localePrefix, boolean compressable, boolean skipToFaceletResourceHelper, FacesContext ctx) { if (library != null) { return library.getHelper().findResource(library, resourceName, localePrefix, compressable, ctx); } else { ResourceInfo resource = null; if (!skipToFaceletResourceHelper) { resource = webappResourceHelper.findResource(null, resourceName, localePrefix, compressable, ctx); } if (resource == null && !skipToFaceletResourceHelper) { resource = classpathResourceHelper.findResource(null, resourceName, localePrefix, compressable, ctx); } if (resource == null) { resource = faceletWebappResourceHelper.findResource(library, resourceName, localePrefix, compressable, ctx); } return resource; } } ResourceInfo findResource(String resourceId) { // PENDING(fcaputo) do we need to handle contracts here? String libraryName = null; String resourceName = null; int end = 0, start = 0; if (-1 != (end = resourceId.lastIndexOf("/"))) { resourceName = resourceId.substring(end+1); if (-1 != (start = resourceId.lastIndexOf("/", end - 1))) { libraryName = resourceId.substring(start+1, end); } else { libraryName = resourceId.substring(0, end); } } FacesContext context = FacesContext.getCurrentInstance(); LibraryInfo info = this.findLibrary(libraryName, null, null, context); ResourceInfo resourceInfo = this.findResource(info, resourceName, libraryName, true, false, context); return resourceInfo; } /** * <p> * Obtains the application configured message resources for the current * request locale. If a ResourceBundle is found and contains the key * <code>javax.faces.resource.localePrefix</code>, use the value associated * with that key as the prefix for locale specific resources. * </p> * * <p> * For example, say the request locale is en_US, and * <code>javax.faces.resourceLocalePrefix</code> is found with a value of * <code>en</code>, a resource path within a web application might look like * <code>/resources/en/corp/images/greetings.jpg</code> * </p> * * @param context the {@link FacesContext} for the current request * @return the localePrefix based on the current request, or <code>null</code> * if no prefix can be determined */ private String getLocalePrefix(FacesContext context) { String localePrefix = null; localePrefix = context.getExternalContext().getRequestParameterMap().get("loc"); if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){ return localePrefix; } String appBundleName = context.getApplication().getMessageBundle(); if (null != appBundleName) { Locale locale = null; if (context.getViewRoot() != null) { locale = context.getViewRoot().getLocale(); } else { locale = context.getApplication().getViewHandler().calculateLocale(context); } try { ResourceBundle appBundle = ResourceBundle.getBundle(appBundleName, locale, Util.getCurrentLoader(ResourceManager.class)); localePrefix = appBundle .getString(ResourceHandler.LOCALE_PREFIX); } catch (MissingResourceException mre) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Ignoring missing resource", mre); } } } return localePrefix; } private List<String> getResourceLibraryContracts(FacesContext context) { UIViewRoot viewRoot = context.getViewRoot(); if(viewRoot == null) { if(context.getApplication().getResourceHandler().isResourceRequest(context)) { // it is a resource request. look at the parameter con=. String param = context.getExternalContext().getRequestParameterMap().get("con"); if(!nameContainsForbiddenSequence(param) && param != null && param.trim().length() > 0) { return Arrays.asList(param); } } // PENDING(edburns): calculate the contracts! return Collections.emptyList(); } return context.getResourceLibraryContracts(); } /** * @param contentType content-type in question * @param ctx the @{link FacesContext} for the current request * @return <code>true</code> if this resource can be compressed, otherwise * <code>false</code> */ private boolean isCompressable(String contentType, FacesContext ctx) { // No compression when developing. if (contentType == null || ctx.isProjectStage(ProjectStage.Development)) { return false; } else { if (compressableTypes != null && !compressableTypes.isEmpty()) { for (Pattern p : compressableTypes) { boolean matches = p.matcher(contentType).matches(); if (matches) { return true; } } } } return false; } /** * Init <code>compressableTypes</code> from the configuration. */ private void initCompressableTypes(Map<String, Object> appMap) { WebConfiguration config = WebConfiguration.getInstance(); String value = config.getOptionValue(WebConfiguration.WebContextInitParameter.CompressableMimeTypes); if (value != null && value.length() > 0) { String[] values = Util.split(appMap, value, ","); if (values != null) { for (String s : values) { String pattern = s.trim(); if (!isPatternValid(pattern)) { continue; } if (pattern.endsWith("/*")) { pattern = pattern.substring(0, pattern.indexOf("/*")); pattern += "/[a-z0-9.-]*"; } if (compressableTypes == null) { compressableTypes = new ArrayList<>(values.length); } try { compressableTypes.add(Pattern.compile(pattern)); } catch (PatternSyntaxException pse) { if (LOGGER.isLoggable(Level.WARNING)) { // PENDING i18n LOGGER.log(Level.WARNING, "jsf.resource.mime.type.configration.invalid", new Object[] { pattern, pse.getPattern()}); } } } } } } /** * @param input input mime-type pattern from the configuration * @return <code>true</code> if the input matches the expected pattern, * otherwise <code>false</code> */ private boolean isPatternValid(String input) { return (CONFIG_MIMETYPE_PATTERN.matcher(input).matches()); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_256_1
crossvul-java_data_good_489_1
/******************************************************************************* * Copyright (c) 2018 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.io; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class ZipUtilTest { @Rule public TemporaryFolder dir = new TemporaryFolder(); @Test public void testWriteEntryNormal() throws IOException { File f = dir.newFile("testok.zip"); try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) { ZipEntry e = new ZipEntry("helloworld.txt"); out.putNextEntry(e); out.write("hello world".getBytes()); out.closeEntry(); } ZipFile zf = new ZipFile(f); File subdir = dir.newFolder("extract"); ZipUtil.extract(zf, subdir); assertTrue("File not extracted", new File(subdir, "helloworld.txt").exists()); } @Test public void testWriteEntryPathTraversing() throws IOException { File f = dir.newFile("testnotok.zip"); try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) { ZipEntry e = new ZipEntry("hello/../../world.txt"); out.putNextEntry(e); out.write("hello world".getBytes()); out.closeEntry(); } ZipFile zf = new ZipFile(f); File subdir = dir.newFolder("extract"); try { ZipUtil.extract(zf, subdir); fail("No exception thrown"); } catch (IOException ioe) { assertTrue(ioe.getMessage().startsWith("Zip entry outside destination directory")); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_489_1
crossvul-java_data_bad_4612_5
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_5
crossvul-java_data_good_1883_3
package eu.hinsch.spring.boot.actuator.logview; import org.apache.catalina.ssi.ByteArrayServletOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") public class LogViewEndpointTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private HttpServletResponse response; private LogViewEndpoint logViewEndpoint; private Model model; private long now; @Before public void setUp() { MockitoAnnotations.initMocks(this); logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(), new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets()); model = new ExtendedModelMap(); now = new Date().getTime(); } @Test public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.containsAttribute("files"), is(true)); assertThat(getFileEntries(), hasSize(0)); } @Test public void shouldListSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileNames(), contains("A.log", "B.log", "C.log")); } @Test public void shouldListReverseSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, true, null); // then assertThat(getFileNames(), contains("C.log", "B.log", "A.log")); } @Test public void shouldListSortedBySize() throws Exception { // given createFile("A.log", "xx", now); createFile("B.log", "x", now); createFile("C.log", "xxx", now); // when logViewEndpoint.list(model, SortBy.SIZE, false, null); // then assertThat(getFileNames(), contains("B.log", "A.log", "C.log")); assertThat(getFileSizes(), contains(1L, 2L, 3L)); } @Test public void shouldListSortedByDate() throws Exception { // given // TODO java 8 date api createFile("A.log", "x", now); createFile("B.log", "x", now - 10 * 60 * 1000); createFile("C.log", "x", now - 5 * 60 * 1000); // when logViewEndpoint.list(model, SortBy.MODIFIED, false, null); // then assertThat(getFileNames(), contains("B.log", "C.log", "A.log")); assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago")); } @Test public void shouldSetFileTypeForFile() throws Exception { // given createFile("A.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE)); } @Test public void shouldSetFileTypeForArchive() throws Exception { // given createFile("A.log.tar.gz", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE)); } @Test public void shouldContainEmptyParentLinkInBaseFolder() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder"); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); temporaryFolder.newFolder("subfolder", "nested"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested"); // then assertThat(model.asMap().get("parent"), is("/subfolder")); } @Test public void shouldIncludeSubfolderEntry() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY)); assertThat(fileEntry.getFilename(), is("subfolder")); } @Test public void shouldListZipContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewZipFileContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.zip", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) { ZipEntry zipEntry = new ZipEntry(contentFileName); zos.putNextEntry(zipEntry); IOUtils.write(content, zos); } } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForZip() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.zip", 1, response); // then -> exception } @Test public void shouldListTarGzContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewTarGzFileContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.tar.gz", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.tar.gz", 1, response); // then -> exception } private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream( new BufferedOutputStream(new FileOutputStream( new File(temporaryFolder.getRoot(), archiveFileName)))))) { tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName); archiveEntry.setSize(content.length()); tos.putArchiveEntry(archiveEntry); IOUtils.write(content, tos); tos.closeArchiveEntry(); } } @Test public void shouldRedirectWithoutTrainingSlash() throws IOException { // when logViewEndpoint.redirect(response); // then verify(response).sendRedirect("log/"); } @Test public void shouldEndpointBeSensitive() { assertThat(logViewEndpoint.isSensitive(), is(true)); } @Test public void shouldReturnContextPath() { assertThat(logViewEndpoint.getPath(), is("/log")); } @Test public void shouldReturnNullEndpointType() { assertThat(logViewEndpoint.getEndpointType(), is(nullValue())); } @Test public void shouldNotAllowToListFileOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("may not be located outside base path")); // when logViewEndpoint.view("../somefile", null, null, null); } @Test public void shouldNotAllowToListWithBaseOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("may not be located outside base path")); // when logViewEndpoint.view("somefile", "../otherdir", null, null); } @Test public void shouldViewFile() throws Exception { // given createFile("file.log", "abc", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, null, response); // then assertThat(new String(outputStream.toByteArray()), is("abc")); } @Test public void shouldTailViewOnlyLastLine() throws Exception { // given createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, 1, response); // then assertThat(new String(outputStream.toByteArray()), not(containsString("line1"))); assertThat(new String(outputStream.toByteArray()), containsString("line2")); } @Test public void shouldSearchInFiles() throws Exception { // given String sep = System.lineSeparator(); createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1); createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.search("line2", response); // then String output = new String(outputStream.toByteArray()); assertThat(output, containsString("[A.log] A-line2")); assertThat(output, containsString("[B.log] B-line2")); assertThat(output, not(containsString("line1"))); assertThat(output, not(containsString("line3"))); } private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception { ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); return outputStream; } private List<String> getFileNames() { return getFileEntries() .stream() .map(FileEntry::getFilename) .collect(toList()); } private List<Long> getFileSizes() { return getFileEntries() .stream() .map(FileEntry::getSize) .collect(toList()); } private List<String> getFilePrettyTimes() { return getFileEntries() .stream() .map(FileEntry::getModifiedPretty) .collect(toList()); } private List<FileEntry> getFileEntries() { return (List<FileEntry>) model.asMap().get("files"); } private void createFile(String filename, String content, long modified) throws Exception { File file = new File(temporaryFolder.getRoot(), filename); FileUtils.write(file, content); assertThat(file.setLastModified(modified), is(true)); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_1883_3
crossvul-java_data_bad_489_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_489_0
crossvul-java_data_bad_689_1
package spark.embeddedserver.jetty; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.After; import org.junit.Test; import spark.embeddedserver.EmbeddedServer; import spark.route.Routes; import spark.staticfiles.StaticFilesConfiguration; import static org.mockito.Mockito.*; public class EmbeddedJettyFactoryTest { private EmbeddedServer embeddedServer; @Test public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withThreadPool() throws Exception { final QueuedThreadPool threadPool = new QueuedThreadPool(100); final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool)); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 0,0,0); verify(jettyServerFactory, times(1)).create(threadPool); verifyNoMoreInteractions(jettyServerFactory); } @Test public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); } @After public void tearDown() throws Exception { if(embeddedServer != null) embeddedServer.extinguish(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_689_1
crossvul-java_data_bad_498_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_498_1
crossvul-java_data_bad_688_0
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.resource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import spark.utils.Assert; import spark.utils.ClassUtils; import spark.utils.StringUtils; /** * {@link Resource} implementation for class path resources. * Uses either a given ClassLoader or a given Class for loading resources. * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. * * @author Juergen Hoeller * @author Sam Brannen * @see ClassLoader#getResourceAsStream(String) * @see Class#getResourceAsStream(String) * Code copied from Spring source. Modifications made (mostly removal of methods) by Per Wendel. */ public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class<?> clazz; /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * <p>The thread context class loader will be used for * loading the resource. * * @param path the absolute path within the class path * @see java.lang.ClassLoader#getResourceAsStream(String) * @see spark.utils.ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path) { this(path, null); } /** * Create a new ClassPathResource for ClassLoader usage. * A leading slash will be removed, as the ClassLoader * resource access methods will not accept it. * * @param path the absolute path within the classpath * @param classLoader the class loader to load the resource with, * or {@code null} for the thread context class loader * @see ClassLoader#getResourceAsStream(String) */ public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } private static boolean doesNotContainFileColon(String path) { return !path.contains("file:"); } /** * Create a new ClassPathResource with optional ClassLoader and Class. * Only for internal usage. * * @param path relative or absolute path within the classpath * @param classLoader the class loader to load the resource with, if any * @param clazz the class to load resources with, if any */ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) { this.path = StringUtils.cleanPath(path); this.classLoader = classLoader; this.clazz = clazz; } /** * Return the path for this resource (as resource path within the class path). * * @return the path */ public final String getPath() { return this.path; } /** * This implementation checks for the resolution of a resource URL. * * @return if exists. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public boolean exists() { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } return (url != null); } /** * This implementation opens an InputStream for the given class path resource. * * @return the input stream. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ @Override public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } /** * This implementation returns a URL for the underlying class path resource. * * @return the url. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) { url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } /** * This implementation creates a ClassPathResource, applying the given path * relative to the path of the underlying resource of this descriptor. * * @return the resource. * @see spark.utils.StringUtils#applyRelativePath(String, String) */ @Override public Resource createRelative(String relativePath) { String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); return new ClassPathResource(pathToUse, this.classLoader, this.clazz); } /** * This implementation returns the name of the file that this class path * resource refers to. * * @return the file name. * @see spark.utils.StringUtils#getFilename(String) */ @Override public String getFilename() { return StringUtils.getFilename(this.path); } /** * This implementation returns a description that includes the class path location. * * @return the description. */ @Override public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString(); } /** * This implementation compares the underlying class path locations. * * @return if equals. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; } /** * This implementation returns the hash code of the underlying * class path location. * * @return the hash code. */ @Override public int hashCode() { return this.path.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_688_0
crossvul-java_data_bad_499_0
package cc.mrbird.common.controller; import cc.mrbird.common.exception.FileDownloadException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; @Controller public class CommonController { private Logger log = LoggerFactory.getLogger(this.getClass()); @RequestMapping("common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) throws IOException, FileDownloadException { if (StringUtils.isNotBlank(fileName) && !fileName.endsWith(".xlsx")) throw new FileDownloadException("不支持该类型文件下载"); String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('_') + 1); String filePath = "file/" + fileName; File file = new File(filePath); if (!file.exists()) throw new FileDownloadException("文件未找到"); response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(realFileName, "utf-8")); response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } } catch (Exception e) { log.error("文件下载失败", e); } finally { if (delete) Files.delete(Paths.get(filePath)); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_499_0
crossvul-java_data_bad_4101_0
/** * This file is part of the Goobi viewer - a content presentation and management application for digitized objects. * * Visit these websites for more information. * - http://www.intranda.com * - http://digiverso.com * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.goobi.viewer.controller; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException; import de.unigoettingen.sub.commons.contentlib.exceptions.ServiceNotAllowedException; import io.goobi.viewer.api.rest.AbstractApiUrlManager; import io.goobi.viewer.api.rest.resourcebuilders.TextResourceBuilder; import io.goobi.viewer.exceptions.AccessDeniedException; import io.goobi.viewer.exceptions.DAOException; import io.goobi.viewer.exceptions.HTTPException; import io.goobi.viewer.exceptions.IndexUnreachableException; import io.goobi.viewer.exceptions.PresentationException; import io.goobi.viewer.exceptions.ViewerConfigurationException; import io.goobi.viewer.managedbeans.utils.BeanUtils; /** * Utility class for retrieving data folders, data files and source files. * */ public class DataFileTools { private static final Logger logger = LoggerFactory.getLogger(DataFileTools.class); /** * Retrieves the path to viewer home or repositories root, depending on the record. Used to generate a specific task client query parameter. * * @param pi Record identifier * @return The root folder path of the data repositories; viewer home if none are used * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getDataRepositoryPathForRecord(String pi) throws PresentationException, IndexUnreachableException { String dataRepositoryPath = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getDataRepositoryPath(dataRepositoryPath); } /** * Returns the absolute path to the data repository with the given name (including a slash at the end). Package private to discourage direct usage * by clients. * * @param dataRepositoryPath Data repository name or absolute path * @return * @should return correct path for empty data repository * @should return correct path for data repository name * @should return correct path for absolute data repository path */ static String getDataRepositoryPath(String dataRepositoryPath) { if (StringUtils.isBlank(dataRepositoryPath)) { return DataManager.getInstance().getConfiguration().getViewerHome(); } if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryPath)).isAbsolute()) { return dataRepositoryPath + '/'; } return DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + dataRepositoryPath + '/'; } /** * Constructs the media folder path for the given pi, either directly in viewer-home or within a data repository * * @param pi The work PI. This is both the actual name of the folder and the identifier used to look up data repository in solr * @return A Path to the media folder for the given PI * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getMediaFolder(String pi) throws PresentationException, IndexUnreachableException { return getDataFolder(pi, DataManager.getInstance().getConfiguration().getMediaFolder()); } /** * Returns a map of Paths for each data folder name passed as an argument. * * @param pi The record identifier. This is both the actual name of the folder and the identifier used to look up data repository in Solr * @return HashMap<dataFolderName,Path> * @should return all requested data folders * @param dataFolderNames a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Map<String, Path> getDataFolders(String pi, String... dataFolderNames) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } if (dataFolderNames == null) { throw new IllegalArgumentException("dataFolderNames may not be null"); } String dataRepositoryName = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); Map<String, Path> ret = new HashMap<>(dataFolderNames.length); for (String dataFolderName : dataFolderNames) { ret.put(dataFolderName, getDataFolder(pi, dataFolderName, dataRepositoryName)); } return ret; } /** * Constructs the folder path for data of the given pi, either directly in viewer-home or within a data repository. * * @param pi The record identifier. This is both the actual name of the folder and the identifier used to look up data repository in Solr * @param dataFolderName the data folder within the repository; e.g 'media' or 'alto' * @return A Path to the data folder for the given PI * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFolder(String pi, String dataFolderName) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getDataFolder(pi, dataFolderName, dataRepository); } /** * Returns the data folder path for the given record identifier. To be used in clients that already possess the data repository name. * * @param pi a {@link java.lang.String} object. * @param dataFolderName a {@link java.lang.String} object. * @param dataRepositoryFolder Absolute path to the data repository folder or just the folder name * @should return correct folder if no data repository used * @should return correct folder if data repository used * @return a {@link java.nio.file.Path} object. */ public static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder) { Path repository; // TODO Find a way to use absolute repo paths in unit tests if (StringUtils.isBlank(dataRepositoryFolder)) { repository = Paths.get(DataManager.getInstance().getConfiguration().getViewerHome()); } else if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryFolder)).isAbsolute()) { repository = Paths.get(dataRepositoryFolder); } else { repository = Paths.get(DataManager.getInstance().getConfiguration().getDataRepositoriesHome(), dataRepositoryFolder); } Path folder = repository.resolve(dataFolderName).resolve(pi); return folder; } /** * <p> * getDataFilePath. * </p> * * @param pi Record identifier * @param dataFolderName Name of the data folder (e.g. 'alto') - first choice * @param altDataFolderName Name of the data folder - second choice * @param fileName Name of the content file * @return Path to the requested file * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName) throws PresentationException, IndexUnreachableException { java.nio.file.Path dataFolderPath = getDataFolder(pi, dataFolderName); if (StringUtils.isNotBlank(fileName)) { dataFolderPath = dataFolderPath.resolve(fileName); } if (StringUtils.isNotBlank(altDataFolderName) && !Files.exists(dataFolderPath)) { return getDataFilePath(pi, altDataFolderName, null, fileName); } return dataFolderPath; } /** * <p> * getDataFilePath. * </p> * * @param pi Record identifier * @param relativeFilePath File path relative to data repositories root * @return File represented by the relative file path * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFilePath(String pi, String relativeFilePath) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } String dataRepositoryName = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); String dataRepositoryPath = getDataRepositoryPath(dataRepositoryName); return Paths.get(dataRepositoryPath, relativeFilePath); } /** * Returns the absolute path to the source (METS/LIDO) file with the given file name. * * @param fileName a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getSourceFilePath(String fileName, String format) throws PresentationException, IndexUnreachableException { String pi = FilenameUtils.getBaseName(fileName); String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getSourceFilePath(fileName, dataRepository, format); } /** * Returns the absolute path to the source (METS/LIDO/DENKXWEB/DUBLINCORE) file with the given file name. * * @param fileName a {@link java.lang.String} object. * @param dataRepository a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @should construct METS file path correctly * @should construct LIDO file path correctly * @should construct DenkXweb file path correctly * @should throw IllegalArgumentException if fileName is null * @should throw IllegalArgumentException if format is unknown * @return a {@link java.lang.String} object. */ public static String getSourceFilePath(String fileName, String dataRepository, String format) { if (StringUtils.isEmpty(fileName)) { throw new IllegalArgumentException("fileName may not be null or empty"); } if (StringUtils.isEmpty(format)) { throw new IllegalArgumentException("format may not be null or empty"); } switch (format) { case SolrConstants._METS: case SolrConstants._LIDO: case SolrConstants._DENKXWEB: case SolrConstants._WORLDVIEWS: case SolrConstants._DUBLINCORE: break; default: throw new IllegalArgumentException("format must be: METS | LIDO | DENKXWEB | DUBLINCORE | WORLDVIEWS"); } StringBuilder sb = new StringBuilder(getDataRepositoryPath(dataRepository)); switch (format) { case SolrConstants._METS: sb.append(DataManager.getInstance().getConfiguration().getIndexedMetsFolder()); break; case SolrConstants._LIDO: sb.append(DataManager.getInstance().getConfiguration().getIndexedLidoFolder()); break; case SolrConstants._DENKXWEB: sb.append(DataManager.getInstance().getConfiguration().getIndexedDenkxwebFolder()); break; case SolrConstants._DUBLINCORE: sb.append(DataManager.getInstance().getConfiguration().getIndexedDublinCoreFolder()); break; case SolrConstants._WORLDVIEWS: sb.append(DataManager.getInstance().getConfiguration().getIndexedMetsFolder()); break; } sb.append('/').append(fileName); return sb.toString(); } /** * <p> * getTextFilePath. * </p> * * @param pi a {@link java.lang.String} object. * @param fileName a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @should return correct path * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getTextFilePath(String pi, String fileName, String format) throws PresentationException, IndexUnreachableException { if (StringUtils.isEmpty(fileName)) { throw new IllegalArgumentException("fileName may not be null or empty"); } if (StringUtils.isEmpty(format)) { throw new IllegalArgumentException("format may not be null or empty"); } String dataFolderName = null; switch (format) { case SolrConstants.FILENAME_ALTO: dataFolderName = DataManager.getInstance().getConfiguration().getAltoFolder(); break; case SolrConstants.FILENAME_FULLTEXT: dataFolderName = DataManager.getInstance().getConfiguration().getFulltextFolder(); break; case SolrConstants.FILENAME_TEI: dataFolderName = DataManager.getInstance().getConfiguration().getTeiFolder(); break; } return getDataFilePath(pi, dataFolderName, null, fileName).toAbsolutePath().toString(); } /** * <p> * getTextFilePath. * </p> * * @param pi a {@link java.lang.String} object. * @param relativeFilePath ALTO/text file path relative to the data folder * @return a {@link java.nio.file.Path} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getTextFilePath(String pi, String relativeFilePath) throws PresentationException, IndexUnreachableException { if (StringUtils.isBlank(relativeFilePath)) { return null; } String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); Path filePath = Paths.get(getDataRepositoryPath(dataRepository), relativeFilePath); return filePath; } /** * Loads plain full-text via the REST service. ALTO is preferred (and converted to plain text, with a plain text fallback. * * @param altoFilePath ALTO file path relative to the repository root (e.g. "alto/PPN123/00000001.xml") * @param fulltextFilePath plain full-text file path relative to the repository root (e.g. "fulltext/PPN123/00000001.xml") * @param mergeLineBreakWords a boolean. * @param request a {@link javax.servlet.http.HttpServletRequest} object. * @should load fulltext from alto correctly * @should load fulltext from plain text correctly * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.AccessDeniedException if any. * @throws java.io.FileNotFoundException if any. * @throws java.io.IOException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. * @throws io.goobi.viewer.exceptions.DAOException if any. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. */ public static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords, HttpServletRequest request) throws AccessDeniedException, FileNotFoundException, IOException, IndexUnreachableException, DAOException, ViewerConfigurationException { TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); if (altoFilePath != null) { // ALTO file try { String alto = builder.getAltoDocument(FileTools.getBottomFolderFromPathString(altoFilePath), FileTools.getFilenameFromPathString(altoFilePath)); if (alto != null) { return ALTOTools.getFullText(alto, mergeLineBreakWords, request); } } catch (ContentNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } catch (PresentationException e) { logger.error(e.getMessage()); } } if (fulltextFilePath != null) { // Plain full-text file try { String fulltext = builder.getFulltext(FileTools.getBottomFolderFromPathString(fulltextFilePath), FileTools.getFilenameFromPathString(fulltextFilePath)); if (fulltext != null) { return fulltext; } } catch (ContentNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } catch (PresentationException e) { logger.error(e.getMessage()); } } return null; } public static String loadAlto(String altoFilePath) throws ContentNotFoundException, AccessDeniedException, IndexUnreachableException, DAOException, PresentationException { TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); if (altoFilePath != null) { // ALTO file try { String alto = builder.getAltoDocument(FileTools.getBottomFolderFromPathString(altoFilePath), FileTools.getFilenameFromPathString(altoFilePath)); return alto; } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } } else throw new ContentNotFoundException("Alto file " + altoFilePath + " not found"); } /** * <p> * loadTei. * </p> * * @param pi a {@link java.lang.String} object. * @param language a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.AccessDeniedException if any. * @throws java.io.FileNotFoundException if any. * @throws java.io.IOException if any. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. */ public static String loadTei(String pi, String language) throws AccessDeniedException, FileNotFoundException, IOException, ViewerConfigurationException { logger.trace("loadTei: {}/{}", pi, language); if (pi == null) { return null; } TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); try { return builder.getTeiDocument(pi, language); } catch (PresentationException | IndexUnreachableException | DAOException | ContentLibException e) { logger.error(e.toString()); return null; } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4101_0
crossvul-java_data_good_54_1
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import java.io.IOException; import java.lang.reflect.Method; import java.math.BigInteger; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.Buffer; import org.junit.Test; import retrofit2.helpers.NullObjectConverterFactory; import retrofit2.helpers.ToStringConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.HEAD; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.HeaderMap; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.OPTIONS; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import retrofit2.http.QueryName; import retrofit2.http.Url; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @SuppressWarnings({"UnusedParameters", "unused"}) // Parameters inspected reflectively. public final class RequestFactoryTest { private static final MediaType TEXT_PLAIN = MediaType.get("text/plain"); @Test public void customMethodNoBody() { class Example { @HTTP(method = "CUSTOM1", path = "/foo") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM1"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertThat(request.body()).isNull(); } @Test public void customMethodWithBody() { class Example { @HTTP(method = "CUSTOM2", path = "/foo", hasBody = true) Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("CUSTOM2"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo"); assertBody(request.body(), "hi"); } @Test public void onlyOneEncodingIsAllowedMultipartFirst() { class Example { @Multipart // @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void onlyOneEncodingIsAllowedFormEncodingFirst() { class Example { @FormUrlEncoded // @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void invalidPathParam() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Path("hey!") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}." + " Found: hey! (parameter #1)\n for method Example.method"); } } @Test public void pathParamNotAllowedInQuery() throws Exception { class Example { @GET("/foo?bar={bar}") // Call<ResponseBody> method(@Path("bar") String thing) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL query string \"bar={bar}\" must not have replace block." + " For dynamic query parameters use @Query.\n for method Example.method"); } } @Test public void multipleParameterAnnotationsNotAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Body @Query("nope") String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method"); } } @interface NonNull {} @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception { class Example { @GET("/") // Call<ResponseBody> method(@Query("maybe") @NonNull Object o) { return null; } } Request request = buildRequest(Example.class, "yep"); assertThat(request.url().toString()).isEqualTo("http://example.com/?maybe=yep"); } @Test public void twoMethodsFail() { class Example { @PATCH("/foo") // @POST("/foo") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .isIn("Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method", "Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method"); } } @Test public void lackingMethod() { class Example { Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method"); } } @Test public void implicitMultipartForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Part("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitMultipartWithPartMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@PartMap Map<String, String> params) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"); } } @Test public void multipartFailsOnNonBodyMethod() { class Example { @Multipart // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void multipartFailsWithNoParts() { class Example { @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multipart method must contain at least one @Part.\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@Field("a") int a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void implicitFormEncodingByFieldMapForbidden() { class Example { @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method"); } } @Test public void formEncodingFailsOnNonBodyMethod() { class Example { @FormUrlEncoded // @GET("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"); } } @Test public void formEncodingFailsWithNoParts() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Form-encoded method must contain at least one @Field.\n for method Example.method"); } } @Test public void headersFailWhenEmptyOnMethod() { class Example { @GET("/") // @Headers({}) // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Headers annotation is empty.\n for method Example.method"); } } @Test public void headersFailWhenMalformed() { class Example { @GET("/") // @Headers("Malformed") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Headers value must be in the form \"Name: Value\". Found: \"Malformed\"\n for method Example.method"); } } @Test public void pathParamNonPathParamAndTypedBytes() { class Example { @PUT("/{a}") // Call<ResponseBody> method(@Path("a") int a, @Path("b") int b, @Body int c) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "URL \"/{a}\" does not contain \"{b}\". (parameter #2)\n for method Example.method"); } } @Test public void parameterWithoutAnnotation() { class Example { @GET("/") // Call<ResponseBody> method(String a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "No Retrofit annotation found. (parameter #1)\n for method Example.method"); } } @Test public void nonBodyHttpMethodWithSingleEntity() { class Example { @GET("/") // Call<ResponseBody> method(@Body String o) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Non-body HTTP method cannot contain @Body.\n for method Example.method"); } } @Test public void queryMapMustBeAMap() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void queryMapSupportsSubclasses() { class Foo extends HashMap<String, String> { } class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Foo a) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); assertThat(request.url().toString()).isEqualTo("http://example.com/?hello=world"); } @Test public void queryMapRejectsNull() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map was null."); } } @Test public void queryMapRejectsNullKeys() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } Map<String, String> queryParams = new LinkedHashMap<>(); queryParams.put("ping", "pong"); queryParams.put(null, "kat"); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map contained null key."); } } @Test public void queryMapRejectsNullValues() { class Example { @GET("/") // Call<ResponseBody> method(@QueryMap Map<String, String> a) { return null; } } Map<String, String> queryParams = new LinkedHashMap<>(); queryParams.put("ping", "pong"); queryParams.put("kit", null); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Query map contained null value for key 'kit'."); } } @Test public void getWithHeaderMap() { class Example { @GET("/search") Call<ResponseBody> method(@HeaderMap Map<String, Object> headers) { return null; } } Map<String, Object> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put("Accept-Charset", "utf-8"); Request request = buildRequest(Example.class, headers); assertThat(request.method()).isEqualTo("GET"); assertThat(request.url().toString()).isEqualTo("http://example.com/search"); assertThat(request.body()).isNull(); assertThat(request.headers().size()).isEqualTo(2); assertThat(request.header("Accept")).isEqualTo("text/plain"); assertThat(request.header("Accept-Charset")).isEqualTo("utf-8"); } @Test public void headerMapMustBeAMap() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap List<String> headers) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@HeaderMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void headerMapSupportsSubclasses() { class Foo extends HashMap<String, String> { } class Example { @GET("/search") Call<ResponseBody> method(@HeaderMap Foo headers) { return null; } } Foo headers = new Foo(); headers.put("Accept", "text/plain"); Request request = buildRequest(Example.class, headers); assertThat(request.url().toString()).isEqualTo("http://example.com/search"); assertThat(request.headers().size()).isEqualTo(1); assertThat(request.header("Accept")).isEqualTo("text/plain"); } @Test public void headerMapRejectsNull() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } try { buildRequest(Example.class, (Map<String, String>) null); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map was null."); } } @Test public void headerMapRejectsNullKeys() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } Map<String, String> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put(null, "utf-8"); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map contained null key."); } } @Test public void headerMapRejectsNullValues() { class Example { @GET("/") Call<ResponseBody> method(@HeaderMap Map<String, String> headers) { return null; } } Map<String, String> headers = new LinkedHashMap<>(); headers.put("Accept", "text/plain"); headers.put("Accept-Charset", null); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Header map contained null value for key 'Accept-Charset'."); } } @Test public void twoBodies() { class Example { @PUT("/") // Call<ResponseBody> method(@Body String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Multiple @Body method annotations found. (parameter #2)\n for method Example.method"); } } @Test public void bodyInNonBodyRequest() { class Example { @Multipart // @PUT("/") // Call<ResponseBody> method(@Part("one") String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method"); } } @Test public void get() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void delete() { class Example { @DELETE("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("DELETE"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertNull(request.body()); } @Test public void head() { class Example { @HEAD("/foo/bar/") // Call<Void> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("HEAD"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headWithoutVoidThrows() { class Example { @HEAD("/foo/bar/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "HEAD method must use Void as response type.\n for method Example.method"); } } @Test public void post() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void put() { class Example { @PUT("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PUT"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void patch() { class Example { @PATCH("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo("PATCH"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), "hi"); } @Test public void options() { class Example { @OPTIONS("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("OPTIONS"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "po ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void getWithUnusedAndInvalidNamedPathParam() { class Example { @GET("/foo/bar/{ping}/{kit,kat}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/%7Bkit,kat%7D/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "po%20ng"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathSegments() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/pong/more"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/more/"); assertThat(request.body()).isNull(); } @Test public void getWithUnencodedPathSegmentsPreventsRequestSplitting() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = false) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/\r\nheader: blue"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz%2F%0D%0Aheader:%20blue/"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedPathStillPreventsRequestSplitting() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "baz/\r\npong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/"); assertThat(request.body()).isNull(); } @Test public void pathParametersAndPathTraversal() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping") String ping) { return null; } } assertMalformedRequest(Example.class, "."); assertMalformedRequest(Example.class, ".."); assertThat(buildRequest(Example.class, "./a").url().encodedPath()) .isEqualTo("/foo/bar/.%2Fa/"); assertThat(buildRequest(Example.class, "a/.").url().encodedPath()) .isEqualTo("/foo/bar/a%2F./"); assertThat(buildRequest(Example.class, "a/..").url().encodedPath()) .isEqualTo("/foo/bar/a%2F../"); assertThat(buildRequest(Example.class, "../a").url().encodedPath()) .isEqualTo("/foo/bar/..%2Fa/"); assertThat(buildRequest(Example.class, "..\\..").url().encodedPath()) .isEqualTo("/foo/bar/..%5C../"); assertThat(buildRequest(Example.class, "%2E").url().encodedPath()) .isEqualTo("/foo/bar/%252E/"); assertThat(buildRequest(Example.class, "%2E%2E").url().encodedPath()) .isEqualTo("/foo/bar/%252E%252E/"); } @Test public void encodedPathParametersAndPathTraversal() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } assertMalformedRequest(Example.class, "."); assertMalformedRequest(Example.class, "%2E"); assertMalformedRequest(Example.class, "%2e"); assertMalformedRequest(Example.class, ".."); assertMalformedRequest(Example.class, "%2E."); assertMalformedRequest(Example.class, "%2e."); assertMalformedRequest(Example.class, ".%2E"); assertMalformedRequest(Example.class, ".%2e"); assertMalformedRequest(Example.class, "%2E%2e"); assertMalformedRequest(Example.class, "%2e%2E"); assertMalformedRequest(Example.class, "./a"); assertMalformedRequest(Example.class, "a/."); assertMalformedRequest(Example.class, "../a"); assertMalformedRequest(Example.class, "a/.."); assertMalformedRequest(Example.class, "a/../b"); assertMalformedRequest(Example.class, "a/%2e%2E/b"); assertThat(buildRequest(Example.class, "...").url().encodedPath()) .isEqualTo("/foo/bar/.../"); assertThat(buildRequest(Example.class, "a..b").url().encodedPath()) .isEqualTo("/foo/bar/a..b/"); assertThat(buildRequest(Example.class, "a..").url().encodedPath()) .isEqualTo("/foo/bar/a../"); assertThat(buildRequest(Example.class, "a..b").url().encodedPath()) .isEqualTo("/foo/bar/a..b/"); assertThat(buildRequest(Example.class, "..b").url().encodedPath()) .isEqualTo("/foo/bar/..b/"); assertThat(buildRequest(Example.class, "..\\..").url().encodedPath()) .isEqualTo("/foo/bar/..%5C../"); } @Test public void dotDotsOkayWhenNotFullPathSegment() { class Example { @GET("/foo{ping}bar/") // Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) { return null; } } assertMalformedRequest(Example.class, "/./"); assertMalformedRequest(Example.class, "/../"); assertThat(buildRequest(Example.class, ".").url().encodedPath()).isEqualTo("/foo.bar/"); assertThat(buildRequest(Example.class, "..").url().encodedPath()).isEqualTo("/foo..bar/"); } @Test public void pathParamRequired() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Path parameter \"ping\" value must not be null."); } } @Test public void getWithQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query(value = "pi%20ng", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "p%20o%20n%20g"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g"); assertThat(request.body()).isNull(); } @Test public void queryParamOptionalOmitsQuery() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); } @Test public void queryParamOptional() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("foo") String foo, @Query("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?foo=bar&kit=kat"); } @Test public void getWithQueryUrlAndParam() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method(@Query("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithQuery() { class Example { @GET("/foo/bar/?hi=mom") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit, @Query("riff") String riff) { return null; } } Request request = buildRequest(Example.class, "pong", "kat", "raff"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff"); assertThat(request.body()).isNull(); } @Test public void getWithQueryThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Query("kit") String kit, @Path("ping") String ping) { return null; } } try { buildRequest(Example.class, "kat", "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @Query. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryNameThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@QueryName String kit, @Path("ping") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, "kat", "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @QueryName. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryMapThenPathThrows() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Path("ping") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "pong"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Path parameter must not come after a @QueryMap. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathAndQueryQuestionMarkParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong?", "kat?"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()) .isEqualTo("http://example.com/foo/bar/pong%3F/?kit=kat%3F"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryAmpersandParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong&", "kat&"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong&/?kit=kat%26"); assertThat(request.body()).isNull(); } @Test public void getWithPathAndQueryHashParam() { class Example { @GET("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "pong#", "kat#"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong%23/?kit=kat%23"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") List<Object> keys) { return null; } } List<Object> values = Arrays.<Object>asList(1, 2, null, "three", "1"); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") Object[] keys) { return null; } } Object[] values = { 1, 2, null, "three", "1" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamPrimitiveArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Query("key") int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=3&key=1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, "pong"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryNameParam() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName(encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, "p%20o%20n%20g"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?p%20o%20n%20g"); assertThat(request.body()).isNull(); } @Test public void queryNameParamOptionalOmitsQuery() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); } @Test public void getWithQueryNameParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName List<Object> keys) { return null; } } List<Object> values = Arrays.<Object>asList(1, 2, null, "three", "1"); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName Object[] keys) { return null; } } Object[] values = { 1, 2, null, "three", "1" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryNameParamPrimitiveArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryName int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&3&1"); assertThat(request.body()).isNull(); } @Test public void getWithQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "kat"); params.put("ping", "pong"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=kat&ping=pong"); assertThat(request.body()).isNull(); } @Test public void getWithEncodedQueryParamMap() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@QueryMap(encoded = true) Map<String, Object> query) { return null; } } Map<String, Object> params = new LinkedHashMap<>(); params.put("kit", "k%20t"); params.put("pi%20ng", "p%20g"); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g"); assertThat(request.body()).isNull(); } @Test public void getAbsoluteUrl() { class Example { @GET("http://example2.com/foo/bar/") Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrl() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrl() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithStringUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "https://example2.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithJavaUriUrlAbsolute() { class Example { @GET Call<ResponseBody> method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create("https://example2.com/foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithUrlAbsoluteSameHost() { class Example { @GET Call<ResponseBody> method(@Url String url) { return null; } } Request request = buildRequest(Example.class, "http://example.com/foo/bar/"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void getWithHttpUrl() { class Example { @GET Call<ResponseBody> method(@Url HttpUrl url) { return null; } } Request request = buildRequest(Example.class, HttpUrl.get("http://example.com/foo/bar/")); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url()).isEqualTo(HttpUrl.get("http://example.com/foo/bar/")); assertThat(request.body()).isNull(); } @Test public void getWithNullUrl() { class Example { @GET Call<ResponseBody> method(@Url HttpUrl url) { return null; } } try { buildRequest(Example.class, (HttpUrl) null); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("@Url parameter is null."); } } @Test public void getWithNonStringUrlThrows() { class Example { @GET Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type." + " (parameter #1)\n" + " for method Example.method"); } } @Test public void getUrlAndUrlParamThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Url cannot be used with @GET URL (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithoutUrlThrows() { class Example { @GET Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Missing either @GET URL or @Url parameter.\n" + " for method Example.method"); } } @Test public void getWithUrlThenPathThrows() { class Example { @GET Call<ResponseBody> method(@Url String url, @Path("hey") String hey) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path parameters may not be used with @Url. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithPathThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@Path("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path can only be used with relative url on @GET (parameter #1)\n" + " for method Example.method"); } } @Test public void getWithQueryThenUrlThrows() { class Example { @GET("foo/bar") Call<ResponseBody> method(@Query("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "hey", "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @Query. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryNameThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@QueryName String name, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @QueryName. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithQueryMapThenUrlThrows() { class Example { @GET Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @QueryMap. (parameter #2)\n" + " for method Example.method"); } } @Test public void getWithUrlThenQuery() { class Example { @GET Call<ResponseBody> method(@Url String url, @Query("hey") String hey) { return null; } } Request request = buildRequest(Example.class, "foo/bar/", "hey!"); assertThat(request.method()).isEqualTo("GET"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hey=hey%21"); } @Test public void postWithUrl() { class Example { @POST Call<ResponseBody> method(@Url String url, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, "http://example.com/foo/bar", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar"); assertBody(request.body(), "hi"); } @Test public void normalPostWithPathParam() { class Example { @POST("/foo/bar/{ping}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/"); assertBody(request.body(), "Hi!"); } @Test public void emptyBody() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Test public void customMethodEmptyBody() { class Example { @HTTP(method = "CUSTOM", path = "/foo/bar/", hasBody = true) // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("CUSTOM"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertBody(request.body(), ""); } @Test public void bodyRequired() { class Example { @POST("/foo/bar/") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Body parameter value must not be null."); } } @Test public void bodyWithPathParams() { class Example { @POST("/foo/bar/{ping}/{kit}/") // Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body, @Path("kit") String kit) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!"); Request request = buildRequest(Example.class, "pong", body, "kat"); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/kat/"); assertBody(request.body(), "Hi!"); } @Test public void simpleMultipart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("kit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( TEXT_PLAIN, "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); } @Test public void multipartArray() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String[] ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { new String[] { "pong1", "pong2" } }); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part RequestBody part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartIterableRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part List<RequestBody> part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartArrayRequiresName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part RequestBody[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartOkHttpPartForbidsName() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("name") MultipartBody.Part part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartOkHttpPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpIterablePart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part List<MultipartBody.Part> part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar"); MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, Arrays.asList(part1, part2)); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"foo\"\r\n") .contains("\r\nbar\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpArrayPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part[] part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar"); MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat"); Request request = buildRequest(Example.class, new Object[] { new MultipartBody.Part[] { part1, part2 } }); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"foo\"\r\n") .contains("\r\nbar\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartOkHttpPartWithFilename() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData("kit", "kit.txt", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"; filename=\"kit.txt\"\r\n") .contains("\r\nkat\r\n--"); } @Test public void multipartIterable() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") List<String> ping) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("pong1", "pong2")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong1\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong2\r\n--"); } @Test public void multipartIterableOkHttpPart() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") List<MultipartBody.Part> part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartArrayOkHttpPart() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") MultipartBody.Part[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part(value = "ping", encoding = "8-bit") String ping, @Part(value = "kit", encoding = "7-bit") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, "pong", RequestBody.create( TEXT_PLAIN, "kat")); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 7-bit") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMap() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMapWithEncoding() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap(encoding = "8-bit") Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", RequestBody.create(null, "kat")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"\r\n") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\npong\r\n--"); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"kit\"") .contains("Content-Transfer-Encoding: 8-bit") .contains("\r\nkat\r\n--"); } @Test public void multipartPartMapRejectsNonStringKeys() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<Object, RequestBody> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap keys must be of type String: class java.lang.Object (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartPartMapRejectsOkHttpPartValues() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, MultipartBody.Part> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap values cannot be MultipartBody.Part. Use @Part List<Part> or a different value type instead. (parameter #1)\n" + " for method Example.method"); } } @Test public void multipartPartMapRejectsNull() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map was null."); } } @Test public void multipartPartMapRejectsNullKeys() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put(null, RequestBody.create(null, "kat")); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map contained null key."); } } @Test public void multipartPartMapRejectsNullValues() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) { return null; } } Map<String, RequestBody> params = new LinkedHashMap<>(); params.put("ping", RequestBody.create(null, "pong")); params.put("kit", null); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Part map contained null value for key 'kit'."); } } @Test public void multipartPartMapMustBeMap() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap List<Object> parts) { return null; } } try { buildRequest(Example.class, Collections.emptyList()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@PartMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void multipartPartMapSupportsSubclasses() throws IOException { class Foo extends HashMap<String, String> { } class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@PartMap Foo parts) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()) .contains("name=\"hello\"") .contains("\r\n\r\nworld\r\n--"); } @Test public void multipartNullRemovesPart() throws IOException { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") String ping, @Part("fizz") String fizz) { return null; } } Request request = buildRequest(Example.class, "pong", null); assertThat(request.method()).isEqualTo("POST"); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains("Content-Disposition: form-data;") .contains("name=\"ping\"") .contains("\r\npong\r\n--"); } @Test public void multipartPartOptional() { class Example { @Multipart // @POST("/foo/bar/") // Call<ResponseBody> method(@Part("ping") RequestBody ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part."); } } @Test public void simpleFormEncoded() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping) { return null; } } Request request = buildRequest(Example.class, "bar", "pong"); assertBody(request.body(), "foo=bar&ping=pong"); } @Test public void formEncodedWithEncodedNameFieldParam() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field(value = "na%20me", encoded = true) String foo) { return null; } } Request request = buildRequest(Example.class, "ba%20r"); assertBody(request.body(), "na%20me=ba%20r"); } @Test public void formEncodedFieldOptional() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping, @Field("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "bar", null, "kat"); assertBody(request.body(), "foo=bar&kit=kat"); } @Test public void formEncodedFieldList() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") List<Object> fields, @Field("kit") String kit) { return null; } } List<Object> values = Arrays.<Object>asList("foo", "bar", null, 3); Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=foo&foo=bar&foo=3&kit=kat"); } @Test public void formEncodedFieldArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") Object[] fields, @Field("kit") String kit) { return null; } } Object[] values = { 1, 2, null, "three" }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=three&kit=kat"); } @Test public void formEncodedFieldPrimitiveArray() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@Field("foo") int[] fields, @Field("kit") String kit) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, values, "kat"); assertBody(request.body(), "foo=1&foo=2&foo=3&kit=kat"); } @Test public void formEncodedWithEncodedNameFieldParamMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap(encoded = true) Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("k%20it", "k%20at"); fieldMap.put("pin%20g", "po%20ng"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "k%20it=k%20at&pin%20g=po%20ng"); } @Test public void formEncodedFieldMap() { class Example { @FormUrlEncoded // @POST("/foo") // Call<ResponseBody> method(@FieldMap Map<String, Object> fieldMap) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("ping", "pong"); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), "kit=kat&ping=pong"); } @Test public void fieldMapRejectsNull() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map was null."); } } @Test public void fieldMapRejectsNullKeys() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put(null, "pong"); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map contained null key."); } } @Test public void fieldMapRejectsNullValues() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Map<String, Object> a) { return null; } } Map<String, Object> fieldMap = new LinkedHashMap<>(); fieldMap.put("kit", "kat"); fieldMap.put("foo", null); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Field map contained null value for key 'foo'."); } } @Test public void fieldMapMustBeAMap() { class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap List<String> a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method"); } } @Test public void fieldMapSupportsSubclasses() throws IOException { class Foo extends HashMap<String, String> { } class Example { @FormUrlEncoded // @POST("/") // Call<ResponseBody> method(@FieldMap Foo a) { return null; } } Foo foo = new Foo(); foo.put("hello", "world"); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo("hello=world"); } @Test public void simpleHeaders() { class Example { @GET("/foo/bar/") @Headers({ "ping: pong", "kit: kat" }) Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headersDoNotOverwriteEachOther() { class Example { @GET("/foo/bar/") @Headers({ "ping: pong", "kit: kat", "kit: -kat", }) Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(3); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.values("kit")).containsOnly("kat", "-kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamToString() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("kit") BigInteger kit) { return null; } } Request request = buildRequest(Example.class, new BigInteger("1234")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(1); assertThat(headers.get("kit")).isEqualTo("1234"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParam() { class Example { @GET("/foo/bar/") // @Headers("ping: pong") // Call<ResponseBody> method(@Header("kit") String kit) { return null; } } Request request = buildRequest(Example.class, "kat"); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get("ping")).isEqualTo("pong"); assertThat(headers.get("kit")).isEqualTo("kat"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamList() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") List<String> kit) { return null; } } Request request = buildRequest(Example.class, Arrays.asList("bar", null, "baz")); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void headerParamArray() { class Example { @GET("/foo/bar/") // Call<ResponseBody> method(@Header("foo") String[] kit) { return null; } } Request request = buildRequest(Example.class, (Object) new String[] { "bar", null, "baz" }); assertThat(request.method()).isEqualTo("GET"); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values("foo")).containsExactly("bar", "baz"); assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.body()).isNull(); } @Test public void contentTypeAnnotationHeaderOverrides() { class Example { @POST("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } @Test public void malformedContentTypeHeaderThrows() { class Example { @POST("/") // @Headers("Content-Type: hello, world!") // Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); try { buildRequest(Example.class, body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Malformed content type: hello, world!\n" + " for method Example.method"); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } @Test public void contentTypeAnnotationHeaderAddsHeaderWithNoBody() { class Example { @DELETE("/") // @Headers("Content-Type: text/not-plain") // Call<ResponseBody> method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.headers().get("Content-Type")).isEqualTo("text/not-plain"); } @Test public void contentTypeParameterHeaderOverrides() { class Example { @POST("/") // Call<ResponseBody> method(@Header("Content-Type") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "Plain"); Request request = buildRequest(Example.class, "text/not-plain", body); assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain"); } @Test public void malformedContentTypeParameterThrows() { class Example { @POST("/") // Call<ResponseBody> method(@Header("Content-Type") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); try { buildRequest(Example.class, "hello, world!", body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Malformed content type: hello, world!"); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } @Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET("ftp://example.org") Call<ResponseBody> get() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Malformed URL. Base: http://example.com/, Relative: ftp://example.org"); } } @Test public void malformedParameterRelativeUrlThrows() { class Example { @GET Call<ResponseBody> get(@Url String relativeUrl) { return null; } } try { buildRequest(Example.class, "ftp://example.org"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Malformed URL. Base: http://example.com/, Relative: ftp://example.org"); } } @Test public void multipartPartsShouldBeInOrder() throws IOException { class Example { @Multipart @POST("/foo") Call<ResponseBody> get(@Part("first") String data, @Part("second") String dataTwo, @Part("third") String dataThree) { return null; } } Request request = buildRequest(Example.class, "firstParam", "secondParam", "thirdParam"); MultipartBody body = (MultipartBody) request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String readBody = buffer.readUtf8(); assertThat(readBody.indexOf("firstParam")).isLessThan(readBody.indexOf("secondParam")); assertThat(readBody.indexOf("secondParam")).isLessThan(readBody.indexOf("thirdParam")); } @Test public void queryParamsSkippedIfConvertedToNull() throws Exception { class Example { @GET("/query") Call<ResponseBody> queryPath(@Query("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); assertThat(request.url().toString()).doesNotContain("Ignored"); } @Test public void queryParamMapsConvertedToNullShouldError() throws Exception { class Example { @GET("/query") Call<ResponseBody> queryPath(@QueryMap Map<String, String> a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Map<String, String> queryMap = Collections.singletonMap("kit", "kat"); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( "Query map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'."); } } @Test public void fieldParamsSkippedIfConvertedToNull() throws Exception { class Example { @FormUrlEncoded @POST("/query") Call<ResponseBody> queryPath(@Field("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); assertThat(request.url().toString()).doesNotContain("Ignored"); } @Test public void fieldParamMapsConvertedToNullShouldError() throws Exception { class Example { @FormUrlEncoded @POST("/query") Call<ResponseBody> queryPath(@FieldMap Map<String, String> a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com") .addConverterFactory(new NullObjectConverterFactory()); Map<String, String> queryMap = Collections.singletonMap("kit", "kat"); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( "Field map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'."); } } private static void assertBody(RequestBody body, String expected) { assertThat(body).isNotNull(); Buffer buffer = new Buffer(); try { body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } } static <T> Request buildRequest(Class<T> cls, Retrofit.Builder builder, Object... args) { okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() { @Override public okhttp3.Call newCall(Request request) { throw new UnsupportedOperationException("Not implemented"); } }; Retrofit retrofit = builder.callFactory(callFactory).build(); Method method = TestingUtils.onlyMethod(cls); try { return RequestFactory.parseAnnotations(retrofit, method).create(args); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } } static <T> Request buildRequest(Class<T> cls, Object... args) { Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("http://example.com/") .addConverterFactory(new ToStringConverterFactory()); return buildRequest(cls, retrofitBuilder, args); } static void assertMalformedRequest(Class<?> cls, Object... args) { try { Request request = buildRequest(cls, args); fail("expected a malformed request but was " + request); } catch (IllegalArgumentException expected) { } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_54_1
crossvul-java_data_bad_68_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_68_1
crossvul-java_data_good_498_0
package cc.mrbird.common.controller; import cc.mrbird.common.exception.FileDownloadException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; @Controller public class CommonController { private Logger log = LoggerFactory.getLogger(this.getClass()); @RequestMapping("common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) throws IOException, FileDownloadException { if (StringUtils.isNotBlank(fileName) && !fileName.endsWith(".xlsx")) throw new FileDownloadException("不支持该类型文件下载"); String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('_') + 1); String filePath = "file/" + fileName; File file = new File(filePath); if (!file.exists()) throw new FileDownloadException("文件未找到"); response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(realFileName, "utf-8")); response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } } catch (Exception e) { log.error("文件下载失败", e); } finally { if (delete) Files.delete(Paths.get(filePath)); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_498_0
crossvul-java_data_good_3993_0
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.api; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.bigbluebutton.api.domain.Recording; import org.bigbluebutton.api.domain.RecordingMetadata; import org.bigbluebutton.api.messaging.messages.MakePresentationDownloadableMsg; import org.bigbluebutton.api.util.RecordingMetadataReaderHelper; import org.bigbluebutton.api2.domain.UploadedTrack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecordingService { private static Logger log = LoggerFactory.getLogger(RecordingService.class); private static String processDir = "/var/bigbluebutton/recording/process"; private static String publishedDir = "/var/bigbluebutton/published"; private static String unpublishedDir = "/var/bigbluebutton/unpublished"; private static String deletedDir = "/var/bigbluebutton/deleted"; private RecordingMetadataReaderHelper recordingServiceHelper; private String recordStatusDir; private String captionsDir; private String presentationBaseDir; private String defaultServerUrl; private String defaultTextTrackUrl; private void copyPresentationFile(File presFile, File dlownloadableFile) { try { FileUtils.copyFile(presFile, dlownloadableFile); } catch (IOException ex) { log.error("Failed to copy file: {}", ex); } } public void processMakePresentationDownloadableMsg(MakePresentationDownloadableMsg msg) { File presDir = Util.getPresentationDir(presentationBaseDir, msg.meetingId, msg.presId); File downloadableFile = new File(presDir.getAbsolutePath() + File.separatorChar + msg.presFilename); if (presDir != null) { if (msg.downloadable) { String fileExt = FilenameUtils.getExtension(msg.presFilename); File presFile = new File(presDir.getAbsolutePath() + File.separatorChar + msg.presId + "." + fileExt); log.info("Make file downloadable. {}", downloadableFile.getAbsolutePath()); copyPresentationFile(presFile, downloadableFile); } else { if (downloadableFile.exists()) { if(downloadableFile.delete()) { log.info("File deleted. {}", downloadableFile.getAbsolutePath()); } else { log.warn("Failed to delete. {}", downloadableFile.getAbsolutePath()); } } } } } public File getDownloadablePresentationFile(String meetingId, String presId, String presFilename) { log.info("Find downloadable presentation for meetingId={} presId={} filename={}", meetingId, presId, presFilename); File presDir = Util.getPresentationDir(presentationBaseDir, meetingId, presId); // Build file to presFilename // Get canonicalPath and make sure it starts with // /var/bigbluebutton/<meetingid-pattern> // If so return file, if not return null File presFile = new File(presDir.getAbsolutePath() + File.separatorChar + presFilename); try { String presFileCanonical = presFile.getCanonicalPath(); log.debug("Requested presentation name file full path {}",presFileCanonical); if (presFileCanonical.startsWith(presentationBaseDir)) { return presFile; } } catch (IOException e) { log.error("Exception getting canonical path for {}.\n{}", presFilename, e); return null; } log.error("Cannot find file for {}.", presFilename); return null; } public void kickOffRecordingChapterBreak(String meetingId, Long timestamp) { String done = recordStatusDir + File.separatorChar + meetingId + "-" + timestamp + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create {} file.", done); } catch (IOException e) { log.error("Exception occured when trying to create {} file", done); } } else { log.error("{} file already exists.", done); } } public void startIngestAndProcessing(String meetingId) { String done = recordStatusDir + File.separatorChar + meetingId + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create {} file.", done); } catch (IOException e) { log.error("Exception occured when trying to create {} file.", done); } } else { log.error("{} file already exists.", done); } } public void markAsEnded(String meetingId) { String done = recordStatusDir + "/../ended/" + meetingId + ".done"; File doneFile = new File(done); if (!doneFile.exists()) { try { doneFile.createNewFile(); if (!doneFile.exists()) log.error("Failed to create " + done + " file."); } catch (IOException e) { log.error("Exception occured when trying to create {} file.", done); } } else { log.error(done + " file already exists."); } } public List<RecordingMetadata> getRecordingsMetadata(List<String> recordIDs, List<String> states) { List<RecordingMetadata> recs = new ArrayList<>(); Map<String, List<File>> allDirectories = getAllDirectories(states); if (recordIDs.isEmpty()) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { recordIDs.addAll(getAllRecordingIds(entry.getValue())); } } for (String recordID : recordIDs) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { List<File> _recs = getRecordingsForPath(recordID, entry.getValue()); for (File _rec : _recs) { RecordingMetadata r = getRecordingMetadata(_rec); if (r != null) { recs.add(r); } } } } return recs; } public Boolean validateTextTrackSingleUseToken(String recordId, String caption, String token) { return recordingServiceHelper.validateTextTrackSingleUseToken(recordId, caption, token); } public String getRecordingTextTracks(String recordId) { return recordingServiceHelper.getRecordingTextTracks(recordId, captionsDir, getCaptionFileUrlDirectory()); } public String putRecordingTextTrack(UploadedTrack track) { return recordingServiceHelper.putRecordingTextTrack(track); } public String getRecordings2x(List<String> idList, List<String> states, Map<String, String> metadataFilters) { List<RecordingMetadata> recsList = getRecordingsMetadata(idList, states); ArrayList<RecordingMetadata> recs = filterRecordingsByMetadata(recsList, metadataFilters); return recordingServiceHelper.getRecordings2x(recs); } private RecordingMetadata getRecordingMetadata(File dir) { File file = new File(dir.getPath() + File.separatorChar + "metadata.xml"); return recordingServiceHelper.getRecordingMetadata(file); } public boolean recordingMatchesMetadata(RecordingMetadata recording, Map<String, String> metadataFilters) { boolean matchesMetadata = true; Map<String, String> recMeta = recording.getMeta(); for (Map.Entry<String, String> filter : metadataFilters.entrySet()) { String metadataValue = recMeta.get(filter.getKey()); if ( metadataValue == null ) { // The recording doesn't have metadata specified matchesMetadata = false; } else { String filterValue = filter.getValue(); if( filterValue.charAt(0) == '%' && filterValue.charAt(filterValue.length()-1) == '%' && metadataValue.contains(filterValue.substring(1, filterValue.length()-1)) ){ // Filter value embraced by two wild cards // AND the filter value is part of the metadata value } else if( filterValue.charAt(0) == '%' && metadataValue.endsWith(filterValue.substring(1, filterValue.length())) ) { // Filter value starts with a wild cards // AND the filter value ends with the metadata value } else if( filterValue.charAt(filterValue.length()-1) == '%' && metadataValue.startsWith(filterValue.substring(0, filterValue.length()-1)) ) { // Filter value ends with a wild cards // AND the filter value starts with the metadata value } else if( metadataValue.equals(filterValue) ) { // Filter value doesnt have wildcards // AND the filter value is the same as metadata value } else { matchesMetadata = false; } } } return matchesMetadata; } public ArrayList<RecordingMetadata> filterRecordingsByMetadata(List<RecordingMetadata> recordings, Map<String, String> metadataFilters) { ArrayList<RecordingMetadata> resultRecordings = new ArrayList<>(); for (RecordingMetadata entry : recordings) { if (recordingMatchesMetadata(entry, metadataFilters)) resultRecordings.add(entry); } return resultRecordings; } private ArrayList<File> getAllRecordingsFor(String recordId) { String[] format = getPlaybackFormats(publishedDir); ArrayList<File> ids = new ArrayList<File>(); for (int i = 0; i < format.length; i++) { List<File> recordings = getDirectories(publishedDir + File.separatorChar + format[i]); for (int f = 0; f < recordings.size(); f++) { if (recordId.equals(recordings.get(f).getName())) ids.add(recordings.get(f)); } } return ids; } public boolean isRecordingExist(String recordId) { List<String> publishList = getAllRecordingIds(publishedDir); List<String> unpublishList = getAllRecordingIds(unpublishedDir); if (publishList.contains(recordId) || unpublishList.contains(recordId)) { return true; } return false; } public boolean existAnyRecording(List<String> idList) { List<String> publishList = getAllRecordingIds(publishedDir); List<String> unpublishList = getAllRecordingIds(unpublishedDir); for (String id : idList) { if (publishList.contains(id) || unpublishList.contains(id)) { return true; } } return false; } private List<String> getAllRecordingIds(String path) { String[] format = getPlaybackFormats(path); return getAllRecordingIds(path, format); } private List<String> getAllRecordingIds(String path, String[] format) { List<String> ids = new ArrayList<>(); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (!ids.contains(recording.getName())) { ids.add(recording.getName()); } } } return ids; } private Set<String> getAllRecordingIds(List<File> recs) { Set<String> ids = new HashSet<>(); Iterator<File> iterator = recs.iterator(); while (iterator.hasNext()) { ids.add(iterator.next().getName()); } return ids; } private List<File> getRecordingsForPath(String id, List<File> recordings) { List<File> recs = new ArrayList<>(); Iterator<File> iterator = recordings.iterator(); while (iterator.hasNext()) { File rec = iterator.next(); if (rec.getName().startsWith(id)) { recs.add(rec); } } return recs; } private static void deleteRecording(String id, String path) { String[] format = getPlaybackFormats(path); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (recording.getName().equals(id)) { deleteDirectory(recording); createDirectory(recording); } } } } private static void createDirectory(File directory) { if (!directory.exists()) directory.mkdirs(); } private static void deleteDirectory(File directory) { /** * Go through each directory and check if it's not empty. We need to * delete files inside a directory before a directory can be deleted. **/ File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } // Now that the directory is empty. Delete it. directory.delete(); } private static List<File> getDirectories(String path) { List<File> files = new ArrayList<>(); try { DirectoryStream<Path> stream = Files.newDirectoryStream(FileSystems.getDefault().getPath(path)); Iterator<Path> iter = stream.iterator(); while (iter.hasNext()) { Path next = iter.next(); files.add(next.toFile()); } stream.close(); } catch (IOException e) { e.printStackTrace(); } return files; } private static String[] getPlaybackFormats(String path) { System.out.println("Getting playback formats at " + path); List<File> dirs = getDirectories(path); String[] formats = new String[dirs.size()]; for (int i = 0; i < dirs.size(); i++) { System.out.println("Playback format = " + dirs.get(i).getName()); formats[i] = dirs.get(i).getName(); } return formats; } public void setRecordingStatusDir(String dir) { recordStatusDir = dir; } public void setUnpublishedDir(String dir) { unpublishedDir = dir; } public void setPresentationBaseDir(String dir) { presentationBaseDir = dir; } public void setDefaultServerUrl(String url) { defaultServerUrl = url; } public void setDefaultTextTrackUrl(String url) { defaultTextTrackUrl = url; } public void setPublishedDir(String dir) { publishedDir = dir; } public void setCaptionsDir(String dir) { captionsDir = dir; } public void setRecordingServiceHelper(RecordingMetadataReaderHelper r) { recordingServiceHelper = r; } private boolean shouldIncludeState(List<String> states, String type) { boolean r = false; if (!states.isEmpty()) { if (states.contains("any")) { r = true; } else { if (type.equals(Recording.STATE_PUBLISHED) && states.contains(Recording.STATE_PUBLISHED)) { r = true; } else if (type.equals(Recording.STATE_UNPUBLISHED) && states.contains(Recording.STATE_UNPUBLISHED)) { r = true; } else if (type.equals(Recording.STATE_DELETED) && states.contains(Recording.STATE_DELETED)) { r = true; } else if (type.equals(Recording.STATE_PROCESSING) && states.contains(Recording.STATE_PROCESSING)) { r = true; } else if (type.equals(Recording.STATE_PROCESSED) && states.contains(Recording.STATE_PROCESSED)) { r = true; } } } else { if (type.equals(Recording.STATE_PUBLISHED) || type.equals(Recording.STATE_UNPUBLISHED)) { r = true; } } return r; } public boolean changeState(String recordingId, String state) { boolean succeeded = false; if (state.equals(Recording.STATE_PUBLISHED)) { // It can only be published if it is unpublished succeeded |= changeState(unpublishedDir, recordingId, state); } else if (state.equals(Recording.STATE_UNPUBLISHED)) { // It can only be unpublished if it is published succeeded |= changeState(publishedDir, recordingId, state); } else if (state.equals(Recording.STATE_DELETED)) { // It can be deleted from any state succeeded |= changeState(publishedDir, recordingId, state); succeeded |= changeState(unpublishedDir, recordingId, state); } return succeeded; } private boolean changeState(String path, String recordingId, String state) { boolean exists = false; boolean succeeded = true; String[] format = getPlaybackFormats(path); for (String aFormat : format) { List<File> recordings = getDirectories(path + File.separatorChar + aFormat); for (File recording : recordings) { if (recording.getName().equalsIgnoreCase(recordingId)) { exists = true; File dest; if (state.equals(Recording.STATE_PUBLISHED)) { dest = new File(publishedDir + File.separatorChar + aFormat); succeeded &= publishRecording(dest, recordingId, recording, aFormat); } else if (state.equals(Recording.STATE_UNPUBLISHED)) { dest = new File(unpublishedDir + File.separatorChar + aFormat); succeeded &= unpublishRecording(dest, recordingId, recording, aFormat); } else if (state.equals(Recording.STATE_DELETED)) { dest = new File(deletedDir + File.separatorChar + aFormat); succeeded &= deleteRecording(dest, recordingId, recording, aFormat); } else { log.debug(String.format("State: %s, is not supported", state)); return false; } } } } return exists && succeeded; } public boolean publishRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_PUBLISHED); r.setPublished(true); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to publish recording : " + recordingId, e); } } return false; } public boolean unpublishRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_UNPUBLISHED); r.setPublished(false); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to unpublish recording : " + recordingId, e); } } return false; } public boolean deleteRecording(File destDir, String recordingId, File recordingDir, String format) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(recordingDir.getPath()); RecordingMetadata r = recordingServiceHelper.getRecordingMetadata(metadataXml); if (r != null) { if (!destDir.exists()) destDir.mkdirs(); try { FileUtils.moveDirectory(recordingDir, new File(destDir.getPath() + File.separatorChar + recordingId)); r.setState(Recording.STATE_DELETED); r.setPublished(false); File medataXmlFile = recordingServiceHelper.getMetadataXmlLocation( destDir.getAbsolutePath() + File.separatorChar + recordingId); // Process the changes by saving the recording into metadata.xml return recordingServiceHelper.saveRecordingMetadata(medataXmlFile, r); } catch (IOException e) { log.error("Failed to delete recording : " + recordingId, e); } } return false; } private List<File> getAllDirectories(String state) { List<File> allDirectories = new ArrayList<>(); String dir = getDestinationBaseDirectoryName(state); if ( dir != null ) { String[] formats = getPlaybackFormats(dir); for (String format : formats) { allDirectories.addAll(getDirectories(dir + File.separatorChar + format)); } } return allDirectories; } private Map<String, List<File>> getAllDirectories(List<String> states) { Map<String, List<File>> allDirectories = new HashMap<>(); if ( shouldIncludeState(states, Recording.STATE_PUBLISHED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PUBLISHED); allDirectories.put(Recording.STATE_PUBLISHED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_UNPUBLISHED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_UNPUBLISHED); allDirectories.put(Recording.STATE_UNPUBLISHED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_DELETED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_DELETED); allDirectories.put(Recording.STATE_DELETED, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_PROCESSING) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PROCESSING); allDirectories.put(Recording.STATE_PROCESSING, listedDirectories); } if ( shouldIncludeState(states, Recording.STATE_PROCESSED) ) { List<File> listedDirectories = getAllDirectories(Recording.STATE_PROCESSED); allDirectories.put(Recording.STATE_PROCESSED, listedDirectories); } return allDirectories; } public void updateMetaParams(List<String> recordIDs, Map<String,String> metaParams) { // Define the directories used to lookup the recording List<String> states = new ArrayList<>(); states.add(Recording.STATE_PUBLISHED); states.add(Recording.STATE_UNPUBLISHED); states.add(Recording.STATE_DELETED); // Gather all the existent directories based on the states defined for the lookup Map<String, List<File>> allDirectories = getAllDirectories(states); // Retrieve the actual recording from the directories gathered for the lookup for (String recordID : recordIDs) { for (Map.Entry<String, List<File>> entry : allDirectories.entrySet()) { List<File> recs = getRecordingsForPath(recordID, entry.getValue()); // Go through all recordings of all formats for (File rec : recs) { File metadataXml = recordingServiceHelper.getMetadataXmlLocation(rec.getPath()); updateRecordingMetadata(metadataXml, metaParams, metadataXml); } } } } public void updateRecordingMetadata(File srxMetadataXml, Map<String,String> metaParams, File destMetadataXml) { RecordingMetadata rec = recordingServiceHelper.getRecordingMetadata(srxMetadataXml); Map<String, String> recMeta = rec.getMeta(); if (rec != null && !recMeta.isEmpty()) { for (Map.Entry<String,String> meta : metaParams.entrySet()) { if ( !"".equals(meta.getValue()) ) { // As it has a value, if the meta parameter exists update it, otherwise add it recMeta.put(meta.getKey(), meta.getValue()); } else { // As it doesn't have a value, if it exists delete it if ( recMeta.containsKey(meta.getKey()) ) { recMeta.remove(meta.getKey()); } } } rec.setMeta(recMeta); // Process the changes by saving the recording into metadata.xml recordingServiceHelper.saveRecordingMetadata(destMetadataXml, rec); } } private Map<String,File> indexRecordings(List<File> recs) { Map<String,File> indexedRecs = new HashMap<>(); Iterator<File> iterator = recs.iterator(); while (iterator.hasNext()) { File rec = iterator.next(); indexedRecs.put(rec.getName(), rec); } return indexedRecs; } private String getDestinationBaseDirectoryName(String state) { return getDestinationBaseDirectoryName(state, false); } private String getDestinationBaseDirectoryName(String state, boolean forceDefault) { String baseDir = null; if ( state.equals(Recording.STATE_PROCESSING) || state.equals(Recording.STATE_PROCESSED) ) baseDir = processDir; else if ( state.equals(Recording.STATE_PUBLISHED) ) baseDir = publishedDir; else if ( state.equals(Recording.STATE_UNPUBLISHED) ) baseDir = unpublishedDir; else if ( state.equals(Recording.STATE_DELETED) ) baseDir = deletedDir; else if ( forceDefault ) baseDir = publishedDir; return baseDir; } public String getCaptionTrackInboxDir() { return captionsDir + File.separatorChar + "inbox"; } public String getCaptionsDir() { return captionsDir; } public String getCaptionFileUrlDirectory() { return defaultTextTrackUrl + "/textTrack/"; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_3993_0