proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/scene/internal/triggers/ManualTriggerProvider.java
ManualTriggerProvider
createDefaultVariable
class ManualTriggerProvider implements SceneTriggerProvider<ManualTrigger> { public static final String PROVIDER = "manual"; @Override public String getProvider() { return PROVIDER; } @Override public String getName() { return "手动触发"; } @Override public ManualTrigger newConfig() { return new ManualTrigger(); } @Override public SqlRequest createSql(ManualTrigger config, List<Term> terms, boolean hasWhere) { return EmptySqlRequest.INSTANCE; } @Override public SqlFragments createFilter(ManualTrigger config, List<Term> terms) { return EmptySqlFragments.INSTANCE; } @Override public List<Variable> createDefaultVariable(ManualTrigger config) {<FILL_FUNCTION_BODY>} @Override public Flux<TermColumn> parseTermColumns(ManualTrigger config) { return Flux.empty(); } @Override public void applyRuleNode(ManualTrigger config, RuleModel model, RuleNodeModel sceneNode) { } }
return Collections.singletonList( Variable .of("_now", LocaleUtils.resolveMessage( "message.scene_term_column_now", "服务器时间")) .withType(DateTimeType.ID) .withTermType(TermTypes.lookup(DateTimeType.GLOBAL)) .withColumn("_now") );
303
98
401
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/scene/internal/triggers/TimerTriggerProvider.java
TimerTriggerProvider
createDefaultVariable
class TimerTriggerProvider implements SceneTriggerProvider<TimerTrigger> { public static final String PROVIDER = "timer"; @Override public String getProvider() { return PROVIDER; } @Override public String getName() { return "手动触发"; } @Override public TimerTrigger newConfig() { return new TimerTrigger(); } @Override public SqlRequest createSql(TimerTrigger config, List<Term> terms, boolean hasWhere) { return EmptySqlRequest.INSTANCE; } @Override public SqlFragments createFilter(TimerTrigger config, List<Term> terms) { return EmptySqlFragments.INSTANCE; } @Override public List<Variable> createDefaultVariable(TimerTrigger config) {<FILL_FUNCTION_BODY>} @Override public Flux<TermColumn> parseTermColumns(TimerTrigger config) { return Flux.empty(); } @Override public void applyRuleNode(TimerTrigger config, RuleModel model, RuleNodeModel sceneNode) { RuleNodeModel timerNode = new RuleNodeModel(); timerNode.setId("scene:timer"); timerNode.setName("定时触发场景"); timerNode.setExecutor("timer"); //使用最小负载节点来执行定时 timerNode.setConfiguration(FastBeanCopier.copy(config, new HashMap<>())); model.getNodes().add(timerNode); //定时->场景 model.link(timerNode, sceneNode); } }
return Collections.singletonList( Variable .of("_now", LocaleUtils.resolveMessage( "message.scene_term_column_now", "服务器时间")) .withType(DateTimeType.ID) .withTermType(TermTypes.lookup(DateTimeType.GLOBAL)) .withColumn("_now") );
416
98
514
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/scene/term/TermColumn.java
TermColumn
of
class TermColumn { @Schema(description = "条件列") private String column; @Schema(description = "名称") private String name; @Schema(description = "全名") private String fullName; @Schema(description = "说明") private String description; @Schema(description = "数据类型") private String dataType; @Schema(description = "是否为物模型列") private boolean metadata; /** * @see Term#getTermType() */ @Schema(description = "支持的条件类型") private List<TermType> termTypes; @Schema(description = "支持的指标") private List<PropertyMetric> metrics; @Schema(description = "可选内容") private List<PropertyMetric> options; @Schema(description = "子列,在类型为object时有值") private List<TermColumn> children; public TermColumn withMetadataTrue() { metadata = true; return this; } public TermColumn copyColumn(Predicate<String> childrenPredicate) { TermColumn copy = FastBeanCopier.copy(this, new TermColumn()); if (CollectionUtils.isNotEmpty(children)) { copy.setChildren( children.stream() .filter(child -> childrenPredicate.test(child.getColumn())) .map(child -> child.copyColumn(childrenPredicate)) .collect(Collectors.toList()) ); } return copy; } public boolean hasColumn(Collection<String> columns) { for (String column : columns) { if (hasColumn(column)) { return true; } } return false; } public boolean hasColumn(String column) { if (this.column.equals(column)) { return true; } if (children == null) { return false; } for (TermColumn child : children) { if (child.hasColumn(column)) { return true; } } return false; } public String getVariable(CharSequence delimiter) { if (column == null) { return null; } String[] arr = column.split("[.]"); if (arr.length == 1) { return arr[0]; } return String.join(delimiter, Arrays.copyOfRange(arr, 1, arr.length)); } @JsonIgnore public String getPropertyOrNull() { if (column == null) { return null; } if (!column.startsWith("properties")) { return null; } String[] arr = column.split("[.]"); return arr[1]; } public PropertyMetric getMetricOrNull(String metric) { if (this.metrics == null) { return null; } for (PropertyMetric propertyMetric : this.metrics) { if (Objects.equals(propertyMetric.getId(), metric)) { return propertyMetric; } } return null; } public TermColumn with(PropertyMetadata metadata) { setColumn(metadata.getId()); setName(metadata.getName()); setDataType(metadata.getValueType().getId()); withMetrics(metadata); setTermTypes(TermTypes.lookup(metadata.getValueType())); return this; } public TermColumn withMetrics(PropertyMetadata metadata) { return withMetrics(PropertyMetadataConstants.Metrics.getMetrics(metadata)); } public TermColumn withMetrics(List<PropertyMetric> metrics) { this.metrics = metrics; return this; } public static TermColumn of(String column, String name, DataType type) { return of(column, name, type, null); } public static TermColumn of(String column, String name, DataType type, String description) {<FILL_FUNCTION_BODY>} public static TermColumn of(PropertyMetadata metadata) { return new TermColumn().with(metadata); } public void refactorDescription(Function<String, TermColumn> columnGetter) { if (!StringUtils.hasText(description)) { doRefactorDescription(columnGetter); } if (children != null) { for (TermColumn child : children) { child.refactorDescription(columnGetter); } } } public void doRefactorDescription(Function<String, TermColumn> columnGetter) { if (CollectionUtils.isNotEmpty(children)) { return; } //属性 if (column.startsWith("properties")) { String[] arr = column.split("[.]"); if (arr.length > 3) { TermColumn column = columnGetter.apply(arr[1]); //类型,report,recent,latest String type = arr[arr.length - 1]; setDescription( DeviceOperation.PropertyValueType .valueOf(type) .getNestDescription(column.name) ); } else { String type = arr[arr.length - 1]; setDescription( DeviceOperation.PropertyValueType .valueOf(type) .getDescription() ); } } } public void refactorFullName(String parentName) { if (StringUtils.hasText(parentName)) { this.fullName = parentName + "/" + name; } else { this.fullName = name; } if (CollectionUtils.isNotEmpty(children)) { for (TermColumn child : children) { child.refactorFullName(this.fullName); } } } }
TermColumn termColumn = new TermColumn(); termColumn.setColumn(column); termColumn.setName(name); termColumn.setDataType(type.getId()); termColumn.setDescription(description); termColumn.setTermTypes(TermTypes.lookup(type)); if (type instanceof EnumType) { List<EnumType.Element> elements = ((EnumType) type).getElements(); if (CollectionUtils.isNotEmpty(elements)) { List<PropertyMetric> options = new ArrayList<>(elements.size()); for (EnumType.Element element : elements) { options.add(PropertyMetric.of(element.getValue(), element.getText(), null)); } termColumn.setOptions(options); } } return termColumn;
1,469
197
1,666
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/scene/term/TermTypes.java
TermTypes
lookup
class TermTypes { private static final Map<String, TermTypeSupport> supports = new LinkedHashMap<>(); static { for (FixedTermTypeSupport value : FixedTermTypeSupport.values()) { register(value); } } public static void register(TermTypeSupport support){ supports.put(support.getType(),support); } public static List<TermType> lookup(DataType dataType) {<FILL_FUNCTION_BODY>} public static Optional<TermTypeSupport> lookupSupport(String type) { return Optional.ofNullable(supports.get(type)); } }
return supports .values() .stream() .filter(support -> support.isSupported(dataType)) .map(TermTypeSupport::type) .collect(Collectors.toList());
158
57
215
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/scene/value/TermValue.java
TermValue
of
class TermValue implements Serializable { private static final long serialVersionUID = 1; @Schema(description = "来源") private Source source; @Schema(description = "[source]为[manual]时不能为空") private Object value; @Schema(description = "[source]为[metric]时不能为空") private String metric; public static TermValue manual(Object value) { TermValue termValue = new TermValue(); termValue.setValue(value); termValue.setSource(Source.manual); return termValue; } public static TermValue metric(String metric) { TermValue termValue = new TermValue(); termValue.setMetric(metric); termValue.setSource(Source.metric); return termValue; } public static List<TermValue> of(Term term) { return of(term.getValue()); } public static List<TermValue> of(Object value) {<FILL_FUNCTION_BODY>} public enum Source { manual, metric, variable, upper } }
if (value == null) { return Collections.emptyList(); } if (value instanceof Map) { return Collections.singletonList(FastBeanCopier.copy(value, new TermValue())); } if (value instanceof TermValue) { return Collections.singletonList(((TermValue) value)); } if (value instanceof Collection) { return ((Collection<?>) value) .stream() .flatMap(val -> of(val).stream()) .collect(Collectors.toList()); } return Collections.singletonList(TermValue.manual(value));
286
161
447
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/AlarmConfigService.java
AlarmConfigService
queryDetailPager
class AlarmConfigService extends GenericReactiveCrudService<AlarmConfigEntity, String> { private final AlarmRecordService alarmRecordService; private final ReactiveRepository<AlarmHandleHistoryEntity, String> handleHistoryRepository; private final SceneService sceneService; /** * 处理告警 * * @param info 告警处理信息 */ public Mono<Void> handleAlarm(AlarmHandleInfo info){ return alarmRecordService .changeRecordState(info.getState(), info.getAlarmRecordId()) .flatMap(total-> { if (total > 0){ return handleHistoryRepository .save(AlarmHandleHistoryEntity.of(info)); }else { return Mono.error(new BusinessException("error.the_alarm_record_has_been_processed")); } }) .then(); } public Mono<PagerResult<AlarmConfigDetail>> queryDetailPager(QueryParamEntity query) {<FILL_FUNCTION_BODY>} /** * 转换为详情信息 * * @param entity 告警配置 * @return 告警配置详情 */ private Mono<AlarmConfigDetail> convertDetail(AlarmConfigEntity entity) { return sceneService .createQuery() .and(SceneEntity::getId, "alarm-bind-rule", entity.getId()) .fetch() .collectList() .map(sceneInfo -> AlarmConfigDetail .of(entity) .withScene(sceneInfo)); } //同步场景修改后的数据到告警配置中 @EventListener @Deprecated public void handleSceneSaved(EntitySavedEvent<SceneEntity> event) { event.async(Mono.defer(() -> Flux .fromIterable(event.getEntity()) .flatMap(this::updateByScene) .then())); } //同步场景修改后的数据到告警配置中 @EventListener @Deprecated public void handleSceneSaved(EntityModifyEvent<SceneEntity> event) { Map<String, SceneEntity> before = event .getBefore() .stream() .collect(Collectors.toMap(SceneEntity::getId, Function.identity())); event.async( Flux.fromIterable(event.getAfter()) .filter(scene -> StringUtils.hasText(scene.getName()) && before.get(scene.getId()) != null && ( !Objects.equals(before.get(scene.getId()).getName(), scene.getName()) || !Objects.equals(before.get(scene.getId()).getTriggerType(), scene.getTriggerType()) ) ) .flatMap(this::updateByScene) ); } @Deprecated public Mono<Void> updateByScene(SceneEntity entity) { return createUpdate() .set(AlarmConfigEntity::getSceneName, entity.getName()) .set(AlarmConfigEntity::getSceneTriggerType, entity.getTriggerType()) .where(AlarmConfigEntity::getSceneId, entity.getId()) .execute() .then(); } public Mono<Void> enable(String id) { return createUpdate() .set(AlarmConfigEntity::getState, AlarmState.enabled) .where(AlarmConfigEntity::getId, id) .execute() .then(); } public Mono<Void> disable(String id) { return createUpdate() .set(AlarmConfigEntity::getState, AlarmState.disabled) .where(AlarmConfigEntity::getId, id) .execute() .then(); } }
return this .queryPager(query) .flatMap(result -> Flux .fromIterable(result.getData()) .index() .flatMap(tp2 -> this // 转换为详情 .convertDetail(tp2.getT2()) .map(detail -> Tuples.of(tp2.getT1(), detail))) // 重新排序,因为转为详情是异步的可能导致顺序乱掉 .sort(Comparator.comparingLong(Tuple2::getT1)) .map(Tuple2::getT2) .collectList() .map(detail -> PagerResult.of(result.getTotal(), detail, query)));
981
186
1,167
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/AlarmLevelService.java
AlarmLevelService
initDefaultData
class AlarmLevelService extends GenericReactiveCrudService<AlarmLevelEntity, String> implements CommandLineRunner { public static final String DEFAULT_ALARM_ID = "default-alarm-id"; private Mono<Void> initDefaultData() {<FILL_FUNCTION_BODY>} @Override public void run(String... args) throws Exception { initDefaultData() .subscribe(); } }
return findById(DEFAULT_ALARM_ID) .switchIfEmpty( Mono.fromCallable(() -> { ClassPathResource resource = new ClassPathResource("alarm-level.json"); try (InputStream stream = resource.getInputStream()) { String json = StreamUtils.copyToString(stream, StandardCharsets.UTF_8); List<AlarmLevelInfo> levelInfo = JSON.parseArray(json, AlarmLevelInfo.class); return AlarmLevelEntity.defaultOf(levelInfo); } }) .flatMap(e -> save(e) .thenReturn(e)) ) .then();
113
165
278
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/AlarmRecordService.java
AlarmRecordService
changeRecordState
class AlarmRecordService extends GenericReactiveCrudService<AlarmRecordEntity, String> { /** * 修改告警记录状态 * @param state 修改后的告警记录状态 * @param id 告警记录ID * @return */ public Mono<Integer> changeRecordState(AlarmRecordState state, String id) {<FILL_FUNCTION_BODY>} }
return createUpdate() .set(AlarmRecordEntity::getState, state) .set(AlarmRecordEntity::getHandleTime, System.currentTimeMillis()) .where(AlarmRecordEntity::getId, id) .not(AlarmRecordEntity::getState, state) .execute();
108
79
187
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/ElasticSearchAlarmHistoryService.java
ElasticSearchAlarmHistoryService
init
class ElasticSearchAlarmHistoryService implements AlarmHistoryService { public final static String ALARM_HISTORY_INDEX = "alarm_history"; private final ElasticSearchIndexManager indexManager; private final ElasticSearchService elasticSearchService; public Mono<PagerResult<AlarmHistoryInfo>> queryPager(QueryParam queryParam) { return elasticSearchService.queryPager(ALARM_HISTORY_INDEX, queryParam, AlarmHistoryInfo.class); } public Mono<Void> save(AlarmHistoryInfo historyInfo) { return elasticSearchService.commit(ALARM_HISTORY_INDEX, createData(historyInfo)); } public Mono<Void> save(Flux<AlarmHistoryInfo> historyInfo) { return elasticSearchService.save(ALARM_HISTORY_INDEX, historyInfo.map(this::createData)); } public Mono<Void> save(Mono<AlarmHistoryInfo> historyInfo) { return elasticSearchService.save(ALARM_HISTORY_INDEX, historyInfo.map(this::createData)); } private Map<String, Object> createData(AlarmHistoryInfo info) { return FastBeanCopier.copy(info, new HashMap<>(16)); } public void init() {<FILL_FUNCTION_BODY>} }
indexManager.putIndex( new DefaultElasticSearchIndexMetadata(ALARM_HISTORY_INDEX) .addProperty("id", StringType.GLOBAL) .addProperty("alarmConfigId", StringType.GLOBAL) .addProperty("alarmConfigName", StringType.GLOBAL) .addProperty("alarmRecordId", StringType.GLOBAL) .addProperty("level", IntType.GLOBAL) .addProperty("description", StringType.GLOBAL) .addProperty("alarmTime", DateTimeType.GLOBAL) .addProperty("targetType", StringType.GLOBAL) .addProperty("targetName", StringType.GLOBAL) .addProperty("targetId", StringType.GLOBAL) .addProperty("sourceType", StringType.GLOBAL) .addProperty("sourceName", StringType.GLOBAL) .addProperty("sourceId", StringType.GLOBAL) .addProperty("alarmInfo", StringType.GLOBAL) .addProperty("creatorId", StringType.GLOBAL) .addProperty("bindings", new ArrayType().elementType(StringType.GLOBAL)) ).block(Duration.ofSeconds(10));
353
316
669
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/RuleInstanceService.java
RuleInstanceService
stop
class RuleInstanceService extends GenericReactiveCrudService<RuleInstanceEntity, String> implements CommandLineRunner { @Autowired private RuleEngine ruleEngine; @Autowired private RuleEngineModelParser modelParser; @Autowired private ElasticSearchService elasticSearchService; public Mono<PagerResult<RuleEngineExecuteEventInfo>> queryExecuteEvent(QueryParam queryParam) { return elasticSearchService.queryPager(RuleEngineLoggerIndexProvider.RULE_EVENT_LOG, queryParam, RuleEngineExecuteEventInfo.class); } public Mono<PagerResult<RuleEngineExecuteLogInfo>> queryExecuteLog(QueryParam queryParam) { return elasticSearchService.queryPager(RuleEngineLoggerIndexProvider.RULE_LOG, queryParam, RuleEngineExecuteLogInfo.class); } @Transactional public Mono<Void> stop(String id) {<FILL_FUNCTION_BODY>} @Transactional public Mono<Void> start(String id) { return findById(Mono.just(id)) .flatMap(this::doStart); } private Mono<Void> doStart(RuleInstanceEntity entity) { return Mono.defer(() -> { RuleModel model = entity.toRule(modelParser); return ruleEngine .startRule(entity.getId(), model) .then(createUpdate() .set(RuleInstanceEntity::getState, RuleInstanceState.started) .where(entity::getId) .execute()).then(); }); } @Override public Mono<Integer> deleteById(Publisher<String> idPublisher) { return Flux.from(idPublisher) .flatMap(id -> this.stop(id).thenReturn(id)) .as(super::deleteById); } @Override public void run(String... args) { createQuery() .where() .is(RuleInstanceEntity::getState, RuleInstanceState.started) .fetch() .flatMap(e -> this .doStart(e) .onErrorResume(err -> { log.warn("启动规则[{}]失败", e.getName(), e); return Mono.empty(); })) .subscribe(); } }
return this.ruleEngine .shutdown(id) .then(createUpdate() .set(RuleInstanceEntity::getState, RuleInstanceState.disable) .where(RuleInstanceEntity::getId, id) .execute()) .then();
587
67
654
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/SceneService.java
SceneService
createScene
class SceneService extends GenericReactiveCrudService<SceneEntity, String> implements CommandLineRunner { private final RuleEngine ruleEngine; public Mono<Void> execute(String id, Map<String, Object> data) { long t = System.currentTimeMillis(); data.put("_now", t); data.put("timestamp", t); return ruleEngine .getTasks(id) .filter(task -> task.getJob().getNodeId().equals(id)) .next()//只执行一个 .flatMap(task -> task.execute(RuleData.create(data))) .then(); } public Mono<Void> executeBatch(Flux<SceneExecuteRequest> requestFlux) { long t = System.currentTimeMillis(); return requestFlux .doOnNext(request -> { if (request.getContext() == null) { request.setContext(new HashMap<>()); } request.getContext().put("_now", t); request.getContext().put("timestamp", t); }) .flatMap(request -> ruleEngine .getTasks(request.getId()) .filter(task -> task.getJob().getNodeId().equals(request.getId())) .next()//只执行一个 .flatMap(task -> task.execute(RuleData.create(request.getContext())))) .then(); } @Transactional(rollbackFor = Throwable.class) public Mono<SceneEntity> createScene(SceneRule rule) {<FILL_FUNCTION_BODY>} @Transactional(rollbackFor = Throwable.class) public Mono<SceneEntity> updateScene(String id, SceneRule rule) { rule.setId(id); rule.validate(); SceneEntity entity = new SceneEntity().with(rule); return this .updateById(id, entity) .thenReturn(entity); } @Transactional(rollbackFor = Throwable.class) public Mono<Void> enable(String id) { Assert.hasText(id, "id can not be empty"); long now = System.currentTimeMillis(); return this .createUpdate() .set(SceneEntity::getState, RuleInstanceState.started) .set(SceneEntity::getModifyTime, now) .set(SceneEntity::getStartTime, now) .where(SceneEntity::getId, id) .execute() .then(); } @Transactional public Mono<Void> disabled(String id) { Assert.hasText(id, "id can not be empty"); return this .createUpdate() .set(SceneEntity::getState, RuleInstanceState.disable) .where(SceneEntity::getId, id) .execute() .then(); } @EventListener public void handleSceneSaved(EntitySavedEvent<SceneEntity> event) { event.async( handleEvent(event.getEntity()) ); } @EventListener public void handleSceneSaved(EntityModifyEvent<SceneEntity> event) { event.async( handleEvent(event.getAfter()) ); } @EventListener public void handleSceneSaved(EntityCreatedEvent<SceneEntity> event) { event.async( Flux.fromIterable(event.getEntity()) .map(SceneEntity::getId) .as(this::findById) .collectList() .flatMap(this::handleEvent) ); } private Mono<Void> handleEvent(Collection<SceneEntity> entities) { return Flux .fromIterable(entities) .flatMap(scene -> { //禁用时,停止规则 if (scene.getState() == RuleInstanceState.disable) { return ruleEngine.shutdown(scene.getId()); }else if (scene.getState() == RuleInstanceState.started){ scene.validate(); return ruleEngine.startRule(scene.getId(), scene.toRule().getModel()); } return Mono.empty(); }) .then(); } @EventListener public void handleSceneDelete(EntityDeletedEvent<SceneEntity> event) { for (SceneEntity entity : event.getEntity()) { entity.setState(RuleInstanceState.disable); } event.async( handleEvent(event.getEntity()) ); } @Override public void run(String... args) { createQuery() .where() .is(SceneEntity::getState, RuleInstanceState.started) .fetch() .flatMap(e -> Mono .defer(() -> ruleEngine.startRule(e.getId(), e.toRule().getModel()).then()) .onErrorResume(err -> { log.warn("启动场景[{}]失败", e.getName(), err); return Mono.empty(); })) .subscribe(); } }
if (!StringUtils.hasText(rule.getId())) { rule.setId(IDGenerator.SNOW_FLAKE_STRING.generate()); } rule.validate(); SceneEntity entity = new SceneEntity().with(rule); entity.setState(RuleInstanceState.disable); return this .insert(entity) .thenReturn(entity);
1,315
96
1,411
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/terms/AlarmBindRuleTerm.java
AlarmBindRuleTerm
createFragments
class AlarmBindRuleTerm extends AbstractTermFragmentBuilder { public AlarmBindRuleTerm() { super("alarm-bind-rule", "告警绑定的规则"); } @Override public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {<FILL_FUNCTION_BODY>} }
PrepareSqlFragments sqlFragments = PrepareSqlFragments.of(); if (term.getOptions().contains("not")) { sqlFragments.addSql("not"); } sqlFragments .addSql("exists(select 1 from ", getTableName("s_alarm_rule_bind", column), " _bind where _bind.rule_id =", columnFullName); List<Object> alarmId = convertList(column, term); sqlFragments .addSql( "and _bind.alarm_id in (", alarmId.stream().map(r -> "?").collect(Collectors.joining(",")), ")") .addParameter(alarmId); sqlFragments.addSql(")"); return sqlFragments;
96
210
306
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/service/terms/RuleBindAlarmTerm.java
RuleBindAlarmTerm
createFragments
class RuleBindAlarmTerm extends AbstractTermFragmentBuilder { public RuleBindAlarmTerm() { super("rule-bind-alarm", "规则绑定的告警"); } @Override public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {<FILL_FUNCTION_BODY>} }
PrepareSqlFragments sqlFragments = PrepareSqlFragments.of(); if (term.getOptions().contains("not")) { sqlFragments.addSql("not"); } sqlFragments .addSql("exists(select 1 from ", getTableName("s_alarm_rule_bind", column), " _bind where _bind.alarm_id =", columnFullName); List<Object> ruleId = convertList(column, term); sqlFragments .addSql( "and _bind.rule_id in (", ruleId.stream().map(r -> "?").collect(Collectors.joining(",")), ")") .addParameter(ruleId); sqlFragments.addSql(")"); return sqlFragments;
96
209
305
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/web/AlarmRuleBindController.java
AlarmRuleBindController
deleteAlarmBind
class AlarmRuleBindController implements ReactiveServiceCrudController<AlarmRuleBindEntity, String> { private final AlarmRuleBindService service; @Override public ReactiveCrudService<AlarmRuleBindEntity, String> getService() { return service; } @PostMapping("/{alarmId}/_delete") @DeleteAction @Operation(summary = "批量删除告警规则绑定") public Mono<Integer> deleteAlarmBind(@PathVariable @Parameter(description = "告警配置ID") String alarmId, @RequestBody @Parameter(description = "场景联动ID") Mono<List<String>> ruleId) {<FILL_FUNCTION_BODY>} }
return ruleId .flatMap(idList -> service .createDelete() .where(AlarmRuleBindEntity::getAlarmId, alarmId) .in(AlarmRuleBindEntity::getRuleId, idList) .execute());
181
67
248
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/web/SceneController.java
SelectorInfo
of
class SelectorInfo { @Schema(description = "ID") private String id; @Schema(description = "名称") private String name; @Schema(description = "说明") private String description; public static SelectorInfo of(DeviceSelectorProvider provider) {<FILL_FUNCTION_BODY>} }
SelectorInfo info = new SelectorInfo(); info.setId(provider.getProvider()); info.setName(LocaleUtils .resolveMessage("message.device_selector_" + provider.getProvider(), provider.getName())); info.setDescription(LocaleUtils .resolveMessage("message.device_selector_" + provider.getProvider() + "_desc", provider.getName())); return info;
88
102
190
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/web/response/AlarmTargetTypeInfo.java
AlarmTargetTypeInfo
of
class AlarmTargetTypeInfo { private String id; private String name; public static AlarmTargetTypeInfo of(AlarmTarget type) {<FILL_FUNCTION_BODY>} }
AlarmTargetTypeInfo info = new AlarmTargetTypeInfo(); info.setId(type.getType()); info.setName(type.getName()); return info;
55
51
106
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-manager/rule-engine-manager/src/main/java/org/jetlinks/community/rule/engine/web/response/SceneRuleInfo.java
SceneRuleInfo
of
class SceneRuleInfo extends SceneRule { @Schema(description = "场景状态") private RuleInstanceState state; @Schema(description = "说明") private String description; @Schema(description = "创建时间") private long createTime; public static SceneRuleInfo of(RuleInstanceEntity instance) {<FILL_FUNCTION_BODY>} }
SceneRuleInfo info = FastBeanCopier.copy(JSON.parseObject(instance.getModelMeta()), new SceneRuleInfo()); info.setState(instance.getState()); info.setId(instance.getId()); info.setCreateTime(info.getCreateTime()); return info;
98
79
177
<methods>public non-sealed void <init>() ,public static java.lang.String createBranchActionId(int, int, int) ,public reactor.core.Disposable createBranchHandler(Flux<Map<java.lang.String,java.lang.Object>>, Function3<java.lang.Integer,java.lang.String,Map<java.lang.String,java.lang.Object>,Mono<java.lang.Void>>) ,public Function<Map<java.lang.String,java.lang.Object>,Mono<java.lang.Boolean>> createDefaultFilter(List<Term>) ,public Function<Map<java.lang.String,java.lang.Object>,Mono<java.lang.Boolean>> createDefaultFilter(SqlFragments) ,public List<org.jetlinks.community.rule.engine.scene.Variable> createDefaultVariable() ,public ShakeLimitGrouping<Map<java.lang.String,java.lang.Object>> createGrouping() ,public SqlRequest createSql(boolean) ,public Flux<org.jetlinks.community.rule.engine.scene.Variable> createVariables(List<org.jetlinks.community.rule.engine.scene.term.TermColumn>, java.lang.Integer, java.lang.Integer, java.lang.Integer) ,public RuleModel toModel() ,public void validate() ,public org.jetlinks.community.rule.engine.scene.SceneRule where(java.lang.String) <variables>public static final java.lang.String ACTION_KEY_ACTION_INDEX,public static final java.lang.String ACTION_KEY_BRANCH_INDEX,public static final java.lang.String ACTION_KEY_GROUP_INDEX,public static final java.lang.String CONTEXT_KEY_SCENE_OUTPUT,public static java.lang.String DEFAULT_FILTER_TABLE,public static final java.lang.String SOURCE_ID_KEY,public static final java.lang.String SOURCE_NAME_KEY,public static final java.lang.String SOURCE_TYPE_KEY,private List<org.jetlinks.community.rule.engine.scene.SceneAction> actions,private List<org.jetlinks.community.rule.engine.scene.SceneConditionAction> branches,private java.lang.String description,private @NotBlank(message = (String)"error.scene_rule_id_cannot_be_blank") String id,private @NotBlank(message = (String)"error.scene_rule_name_cannot_be_blank") String name,private Map<java.lang.String,java.lang.Object> options,private boolean parallel,private List<Term> terms,private @NotNull(message = (String)"error.scene_rule_trigger_cannot_be_null") Trigger trigger
jetlinks_jetlinks-community
jetlinks-community/jetlinks-standalone/src/main/java/org/jetlinks/community/standalone/authorize/LoginEvent.java
LoginEvent
handleLoginSuccess
class LoginEvent { private final UserDetailService detailService; public LoginEvent(UserDetailService detailService) { this.detailService = detailService; } @EventListener public void handleLoginSuccess(AuthorizationSuccessEvent event) {<FILL_FUNCTION_BODY>} }
Map<String, Object> result = event.getResult(); Authentication authentication = event.getAuthentication(); List<Dimension> dimensions = authentication.getDimensions(); result.put("permissions", authentication.getPermissions()); result.put("roles", dimensions); result.put("currentAuthority", authentication.getPermissions().stream().map(Permission::getId).collect(Collectors.toList())); event.async( detailService .findUserDetail(event.getAuthentication().getUser().getId()) .doOnNext(detail -> result.put("user", detail)) );
76
152
228
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-standalone/src/main/java/org/jetlinks/community/standalone/configuration/JetLinksConfiguration.java
JetLinksConfiguration
webServerFactoryWebServerFactoryCustomizer
class JetLinksConfiguration { @Bean public WebServerFactoryCustomizer<NettyReactiveWebServerFactory> webServerFactoryWebServerFactoryCustomizer() {<FILL_FUNCTION_BODY>} @Bean @ConfigurationProperties(prefix = "vertx") public VertxOptions vertxOptions() { return new VertxOptions(); } @Bean public Vertx vertx(VertxOptions vertxOptions) { return Vertx.vertx(vertxOptions); } }
//解决请求参数最大长度问题 return factory -> factory .addServerCustomizers( httpServer -> httpServer.httpRequestDecoder(spec -> { spec.maxInitialLineLength( Math.max(spec.maxInitialLineLength(), (int) DataSize .parse(System.getProperty("server.max-initial-line-length", "100KB")) .toBytes()) ); spec.maxHeaderSize( Math.max(spec.maxHeaderSize(), (int) DataSize .parse(System.getProperty("server.max-header-size", "1MB")) .toBytes()) ); return spec; }));
136
179
315
<no_super_class>
jetlinks_jetlinks-community
jetlinks-community/jetlinks-standalone/src/main/java/org/jetlinks/community/standalone/configuration/JetLinksProperties.java
JetLinksProperties
init
class JetLinksProperties { private String serverId; private String clusterName ="default"; private Map<String, Long> transportLimit; @PostConstruct @SneakyThrows public void init() {<FILL_FUNCTION_BODY>} }
if (serverId == null) { serverId = InetAddress.getLocalHost().getHostName(); }
75
33
108
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/AbstractWatchService.java
AbstractWatchService
check
class AbstractWatchService implements WatchService { private final BlockingQueue<WatchKey> queue = new LinkedBlockingQueue<>(); private final WatchKey poison = new Key(this, null, ImmutableSet.<WatchEvent.Kind<?>>of()); private final AtomicBoolean open = new AtomicBoolean(true); /** * Registers the given watchable with this service, returning a new watch key for it. This * implementation just checks that the service is open and creates a key; subclasses may override * it to do other things as well. */ public Key register(Watchable watchable, Iterable<? extends WatchEvent.Kind<?>> eventTypes) throws IOException { checkOpen(); return new Key(this, watchable, eventTypes); } /** Returns whether or not this watch service is open. */ @VisibleForTesting public boolean isOpen() { return open.get(); } /** Enqueues the given key if the watch service is open; does nothing otherwise. */ final void enqueue(Key key) { if (isOpen()) { queue.add(key); } } /** Called when the given key is cancelled. Does nothing by default. */ public void cancelled(Key key) {} @VisibleForTesting ImmutableList<WatchKey> queuedKeys() { return ImmutableList.copyOf(queue); } @Override public @Nullable WatchKey poll() { checkOpen(); return check(queue.poll()); } @Override public @Nullable WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException { checkOpen(); return check(queue.poll(timeout, unit)); } @Override public WatchKey take() throws InterruptedException { checkOpen(); return check(queue.take()); } /** Returns the given key, throwing an exception if it's the poison. */ private @Nullable WatchKey check(@Nullable WatchKey key) {<FILL_FUNCTION_BODY>} /** Checks that the watch service is open, throwing {@link ClosedWatchServiceException} if not. */ protected final void checkOpen() { if (!open.get()) { throw new ClosedWatchServiceException(); } } @Override public void close() { if (open.compareAndSet(true, false)) { queue.clear(); queue.offer(poison); } } /** A basic implementation of {@link WatchEvent}. */ static final class Event<T> implements WatchEvent<T> { private final Kind<T> kind; private final int count; private final @Nullable T context; public Event(Kind<T> kind, int count, @Nullable T context) { this.kind = checkNotNull(kind); checkArgument(count >= 0, "count (%s) must be non-negative", count); this.count = count; this.context = context; } @Override public Kind<T> kind() { return kind; } @Override public int count() { return count; } @Override public @Nullable T context() { return context; } @Override public boolean equals(Object obj) { if (obj instanceof Event) { Event<?> other = (Event<?>) obj; return kind().equals(other.kind()) && count() == other.count() && Objects.equals(context(), other.context()); } return false; } @Override public int hashCode() { return Objects.hash(kind(), count(), context()); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("kind", kind()) .add("count", count()) .add("context", context()) .toString(); } } /** Implementation of {@link WatchKey} for an {@link AbstractWatchService}. */ static final class Key implements WatchKey { @VisibleForTesting static final int MAX_QUEUE_SIZE = 256; private static WatchEvent<Object> overflowEvent(int count) { return new Event<>(OVERFLOW, count, null); } private final AbstractWatchService watcher; private final Watchable watchable; private final ImmutableSet<WatchEvent.Kind<?>> subscribedTypes; private final AtomicReference<State> state = new AtomicReference<>(State.READY); private final AtomicBoolean valid = new AtomicBoolean(true); private final AtomicInteger overflow = new AtomicInteger(); private final BlockingQueue<WatchEvent<?>> events = new ArrayBlockingQueue<>(MAX_QUEUE_SIZE); public Key( AbstractWatchService watcher, @Nullable Watchable watchable, Iterable<? extends WatchEvent.Kind<?>> subscribedTypes) { this.watcher = checkNotNull(watcher); this.watchable = watchable; // nullable for Watcher poison this.subscribedTypes = ImmutableSet.copyOf(subscribedTypes); } /** Gets the current state of this key, State.READY or SIGNALLED. */ @VisibleForTesting State state() { return state.get(); } /** Gets whether or not this key is subscribed to the given type of event. */ public boolean subscribesTo(WatchEvent.Kind<?> eventType) { return subscribedTypes.contains(eventType); } /** * Posts the given event to this key. After posting one or more events, {@link #signal()} must * be called to cause the key to be enqueued with the watch service. */ public void post(WatchEvent<?> event) { if (!events.offer(event)) { overflow.incrementAndGet(); } } /** * Sets the state to SIGNALLED and enqueues this key with the watcher if it was previously in * the READY state. */ public void signal() { if (state.getAndSet(State.SIGNALLED) == State.READY) { watcher.enqueue(this); } } @Override public boolean isValid() { return watcher.isOpen() && valid.get(); } @Override public List<WatchEvent<?>> pollEvents() { // note: it's correct to be able to retrieve more events from a key without calling reset() // reset() is ONLY for "returning" the key to the watch service to potentially be retrieved by // another thread when you're finished with it List<WatchEvent<?>> result = new ArrayList<>(events.size()); events.drainTo(result); int overflowCount = overflow.getAndSet(0); if (overflowCount != 0) { result.add(overflowEvent(overflowCount)); } return Collections.unmodifiableList(result); } @CanIgnoreReturnValue @Override public boolean reset() { // calling reset() multiple times without polling events would cause key to be placed in // watcher queue multiple times, but not much that can be done about that if (isValid() && state.compareAndSet(State.SIGNALLED, State.READY)) { // requeue if events are pending if (!events.isEmpty()) { signal(); } } return isValid(); } @Override public void cancel() { valid.set(false); watcher.cancelled(this); } @Override public Watchable watchable() { return watchable; } @VisibleForTesting enum State { READY, SIGNALLED } } }
if (key == poison) { // ensure other blocking threads get the poison queue.offer(poison); throw new ClosedWatchServiceException(); } return key;
1,993
50
2,043
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/AclAttributeProvider.java
AclAttributeProvider
get
class AclAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("acl"); private static final ImmutableSet<String> INHERITED_VIEWS = ImmutableSet.of("owner"); private static final ImmutableList<AclEntry> DEFAULT_ACL = ImmutableList.of(); @Override public String name() { return "acl"; } @Override public ImmutableSet<String> inherits() { return INHERITED_VIEWS; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @Override public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) { Object userProvidedAcl = userProvidedDefaults.get("acl:acl"); ImmutableList<AclEntry> acl = DEFAULT_ACL; if (userProvidedAcl != null) { acl = toAcl(checkType("acl", "acl", userProvidedAcl, List.class)); } return ImmutableMap.of("acl:acl", acl); } @Override public @Nullable Object get(File file, String attribute) {<FILL_FUNCTION_BODY>} @Override public void set(File file, String view, String attribute, Object value, boolean create) { if (attribute.equals("acl")) { checkNotCreate(view, attribute, create); file.setAttribute("acl", "acl", toAcl(checkType(view, attribute, value, List.class))); } } @SuppressWarnings("unchecked") // only cast after checking each element's type private static ImmutableList<AclEntry> toAcl(List<?> list) { ImmutableList<?> copy = ImmutableList.copyOf(list); for (Object obj : copy) { if (!(obj instanceof AclEntry)) { throw new IllegalArgumentException( "invalid element for attribute 'acl:acl': should be List<AclEntry>, " + "found element of type " + obj.getClass()); } } return (ImmutableList<AclEntry>) copy; } @Override public Class<AclFileAttributeView> viewType() { return AclFileAttributeView.class; } @Override public AclFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View(lookup, (FileOwnerAttributeView) inheritedViews.get("owner")); } /** Implementation of {@link AclFileAttributeView}. */ private static final class View extends AbstractAttributeView implements AclFileAttributeView { private final FileOwnerAttributeView ownerView; public View(FileLookup lookup, FileOwnerAttributeView ownerView) { super(lookup); this.ownerView = checkNotNull(ownerView); } @Override public String name() { return "acl"; } @SuppressWarnings("unchecked") @Override public List<AclEntry> getAcl() throws IOException { return (List<AclEntry>) lookupFile().getAttribute("acl", "acl"); } @Override public void setAcl(List<AclEntry> acl) throws IOException { checkNotNull(acl); lookupFile().setAttribute("acl", "acl", ImmutableList.copyOf(acl)); } @Override public UserPrincipal getOwner() throws IOException { return ownerView.getOwner(); } @Override public void setOwner(UserPrincipal owner) throws IOException { ownerView.setOwner(owner); } } }
if (attribute.equals("acl")) { return file.getAttribute("acl", "acl"); } return null;
995
39
1,034
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/AttributeProvider.java
AttributeProvider
unsettable
class AttributeProvider { /** Returns the view name that's used to get attributes from this provider. */ public abstract String name(); /** Returns the names of other providers that this provider inherits attributes from. */ public ImmutableSet<String> inherits() { return ImmutableSet.of(); } /** Returns the type of the view interface that this provider supports. */ public abstract Class<? extends FileAttributeView> viewType(); /** * Returns a view of the file located by the given lookup callback. The given map contains the * views inherited by this view. */ public abstract FileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews); /** * Returns a map containing the default attribute values for this provider. The keys of the map * are attribute identifier strings (in "view:attribute" form) and the value for each is the * default value that should be set for that attribute when creating a new file. * * <p>The given map should be in the same format and contains user-provided default values. If the * user provided any default values for attributes handled by this provider, those values should * be checked to ensure they are of the correct type. Additionally, if any changes to a * user-provided attribute are necessary (for example, creating an immutable defensive copy), that * should be done. The resulting values should be included in the result map along with default * values for any attributes the user did not provide a value for. */ public ImmutableMap<String, ?> defaultValues(Map<String, ?> userDefaults) { return ImmutableMap.of(); } /** Returns the set of attributes that are always available from this provider. */ public abstract ImmutableSet<String> fixedAttributes(); /** Returns whether or not this provider supports the given attribute directly. */ public boolean supports(String attribute) { return fixedAttributes().contains(attribute); } /** * Returns the set of attributes supported by this view that are present in the given file. For * most providers, this will be a fixed set of attributes. */ public ImmutableSet<String> attributes(File file) { return fixedAttributes(); } /** * Returns the value of the given attribute in the given file or null if the attribute is not * supported by this provider. */ public abstract @Nullable Object get(File file, String attribute); /** * Sets the value of the given attribute in the given file object. The {@code create} parameter * indicates whether or not the value is being set upon creation of a new file via a user-provided * {@code FileAttribute}. * * @throws IllegalArgumentException if the given attribute is one supported by this provider but * it is not allowed to be set by the user * @throws UnsupportedOperationException if the given attribute is one supported by this provider * and is allowed to be set by the user, but not on file creation and {@code create} is true */ public abstract void set(File file, String view, String attribute, Object value, boolean create); // optional /** * Returns the type of file attributes object this provider supports, or null if it doesn't * support reading its attributes as an object. */ public @Nullable Class<? extends BasicFileAttributes> attributesType() { return null; } /** * Reads this provider's attributes from the given file as an attributes object. * * @throws UnsupportedOperationException if this provider does not support reading an attributes * object */ public BasicFileAttributes readAttributes(File file) { throw new UnsupportedOperationException(); } // exception helpers /** Throws a runtime exception indicating that the given attribute cannot be set. */ protected static RuntimeException unsettable(String view, String attribute, boolean create) {<FILL_FUNCTION_BODY>} /** * Checks that the attribute is not being set by the user on file creation, throwing an * unsupported operation exception if it is. */ protected static void checkNotCreate(String view, String attribute, boolean create) { if (create) { throw new UnsupportedOperationException( "cannot set attribute '" + view + ":" + attribute + "' during file creation"); } } /** * Checks that the given value is of the given type, returning the value if so and throwing an * exception if not. */ protected static <T> T checkType(String view, String attribute, Object value, Class<T> type) { checkNotNull(value); if (type.isInstance(value)) { return type.cast(value); } throw invalidType(view, attribute, value, type); } /** * Throws an illegal argument exception indicating that the given value is not one of the expected * types for the given attribute. */ protected static IllegalArgumentException invalidType( String view, String attribute, Object value, Class<?>... expectedTypes) { Object expected = expectedTypes.length == 1 ? expectedTypes[0] : "one of " + Arrays.toString(expectedTypes); throw new IllegalArgumentException( "invalid type " + value.getClass() + " for attribute '" + view + ":" + attribute + "': expected " + expected); } }
// This matches the behavior of the real file system implementations: if the attempt to set the // attribute is being made during file creation, throw UOE even though the attribute is one // that cannot be set under any circumstances checkNotCreate(view, attribute, create); throw new IllegalArgumentException("cannot set attribute '" + view + ":" + attribute + "'");
1,334
88
1,422
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/BasicAttributeProvider.java
BasicAttributeProvider
get
class BasicAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of( "size", "fileKey", "isDirectory", "isRegularFile", "isSymbolicLink", "isOther", "creationTime", "lastAccessTime", "lastModifiedTime"); @Override public String name() { return "basic"; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @Override public @Nullable Object get(File file, String attribute) {<FILL_FUNCTION_BODY>} @Override public void set(File file, String view, String attribute, Object value, boolean create) { switch (attribute) { case "creationTime": checkNotCreate(view, attribute, create); file.setCreationTime(checkType(view, attribute, value, FileTime.class)); break; case "lastAccessTime": checkNotCreate(view, attribute, create); file.setLastAccessTime(checkType(view, attribute, value, FileTime.class)); break; case "lastModifiedTime": checkNotCreate(view, attribute, create); file.setLastModifiedTime(checkType(view, attribute, value, FileTime.class)); break; case "size": case "fileKey": case "isDirectory": case "isRegularFile": case "isSymbolicLink": case "isOther": throw unsettable(view, attribute, create); default: } } @Override public Class<BasicFileAttributeView> viewType() { return BasicFileAttributeView.class; } @Override public BasicFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View(lookup); } @Override public Class<BasicFileAttributes> attributesType() { return BasicFileAttributes.class; } @Override public BasicFileAttributes readAttributes(File file) { return new Attributes(file); } /** Implementation of {@link BasicFileAttributeView}. */ private static final class View extends AbstractAttributeView implements BasicFileAttributeView { protected View(FileLookup lookup) { super(lookup); } @Override public String name() { return "basic"; } @Override public BasicFileAttributes readAttributes() throws IOException { return new Attributes(lookupFile()); } @Override public void setTimes( @Nullable FileTime lastModifiedTime, @Nullable FileTime lastAccessTime, @Nullable FileTime createTime) throws IOException { File file = lookupFile(); if (lastModifiedTime != null) { file.setLastModifiedTime(lastModifiedTime); } if (lastAccessTime != null) { file.setLastAccessTime(lastAccessTime); } if (createTime != null) { file.setCreationTime(createTime); } } } /** Implementation of {@link BasicFileAttributes}. */ static class Attributes implements BasicFileAttributes { private final FileTime lastModifiedTime; private final FileTime lastAccessTime; private final FileTime creationTime; private final boolean regularFile; private final boolean directory; private final boolean symbolicLink; private final long size; private final Object fileKey; protected Attributes(File file) { this.lastModifiedTime = file.getLastModifiedTime(); this.lastAccessTime = file.getLastAccessTime(); this.creationTime = file.getCreationTime(); this.regularFile = file.isRegularFile(); this.directory = file.isDirectory(); this.symbolicLink = file.isSymbolicLink(); this.size = file.size(); this.fileKey = file.id(); } @Override public FileTime lastModifiedTime() { return lastModifiedTime; } @Override public FileTime lastAccessTime() { return lastAccessTime; } @Override public FileTime creationTime() { return creationTime; } @Override public boolean isRegularFile() { return regularFile; } @Override public boolean isDirectory() { return directory; } @Override public boolean isSymbolicLink() { return symbolicLink; } @Override public boolean isOther() { return false; } @Override public long size() { return size; } @Override public Object fileKey() { return fileKey; } } }
switch (attribute) { case "size": return file.size(); case "fileKey": return file.id(); case "isDirectory": return file.isDirectory(); case "isRegularFile": return file.isRegularFile(); case "isSymbolicLink": return file.isSymbolicLink(); case "isOther": return !file.isDirectory() && !file.isRegularFile() && !file.isSymbolicLink(); case "creationTime": return file.getCreationTime(); case "lastAccessTime": return file.getLastAccessTime(); case "lastModifiedTime": return file.getLastModifiedTime(); default: return null; }
1,248
192
1,440
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/DirectoryEntry.java
DirectoryEntry
requireDirectory
class DirectoryEntry { private final Directory directory; private final Name name; private final @Nullable File file; @Nullable DirectoryEntry next; // for use in Directory DirectoryEntry(Directory directory, Name name, @Nullable File file) { this.directory = checkNotNull(directory); this.name = checkNotNull(name); this.file = file; } /** Returns {@code true} if and only if this entry represents an existing file. */ public boolean exists() { return file != null; } /** * Checks that this entry exists, throwing an exception if not. * * @return this * @throws NoSuchFileException if this entry does not exist */ @CanIgnoreReturnValue public DirectoryEntry requireExists(Path pathForException) throws NoSuchFileException { if (!exists()) { throw new NoSuchFileException(pathForException.toString()); } return this; } /** * Checks that this entry does not exist, throwing an exception if it does. * * @return this * @throws FileAlreadyExistsException if this entry does not exist */ @CanIgnoreReturnValue public DirectoryEntry requireDoesNotExist(Path pathForException) throws FileAlreadyExistsException { if (exists()) { throw new FileAlreadyExistsException(pathForException.toString()); } return this; } /** * Checks that this entry exists and links to a directory, throwing an exception if not. * * @return this * @throws NoSuchFileException if this entry does not exist * @throws NotDirectoryException if this entry does not link to a directory */ @CanIgnoreReturnValue public DirectoryEntry requireDirectory(Path pathForException) throws NoSuchFileException, NotDirectoryException {<FILL_FUNCTION_BODY>} /** * Checks that this entry exists and links to a symbolic link, throwing an exception if not. * * @return this * @throws NoSuchFileException if this entry does not exist * @throws NotLinkException if this entry does not link to a symbolic link */ @CanIgnoreReturnValue public DirectoryEntry requireSymbolicLink(Path pathForException) throws NoSuchFileException, NotLinkException { requireExists(pathForException); if (!file().isSymbolicLink()) { throw new NotLinkException(pathForException.toString()); } return this; } /** Returns the directory containing this entry. */ public Directory directory() { return directory; } /** Returns the name of this entry. */ public Name name() { return name; } /** * Returns the file this entry links to. * * @throws IllegalStateException if the file does not exist */ public File file() { checkState(exists()); return file; } /** Returns the file this entry links to or {@code null} if the file does not exist */ public @Nullable File fileOrNull() { return file; } @Override public boolean equals(Object obj) { if (obj instanceof DirectoryEntry) { DirectoryEntry other = (DirectoryEntry) obj; return directory.equals(other.directory) && name.equals(other.name) && Objects.equals(file, other.file); } return false; } @Override public int hashCode() { return Objects.hash(directory, name, file); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("directory", directory) .add("name", name) .add("file", file) .toString(); } }
requireExists(pathForException); if (!file().isDirectory()) { throw new NotDirectoryException(pathForException.toString()); } return this;
949
44
993
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/DosAttributeProvider.java
DosAttributeProvider
defaultValues
class DosAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("readonly", "hidden", "archive", "system"); private static final ImmutableSet<String> INHERITED_VIEWS = ImmutableSet.of("basic", "owner"); @Override public String name() { return "dos"; } @Override public ImmutableSet<String> inherits() { return INHERITED_VIEWS; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @Override public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) {<FILL_FUNCTION_BODY>} private static Boolean getDefaultValue(String attribute, Map<String, ?> userProvidedDefaults) { Object userProvidedValue = userProvidedDefaults.get(attribute); if (userProvidedValue != null) { return checkType("dos", attribute, userProvidedValue, Boolean.class); } return false; } @Override public @Nullable Object get(File file, String attribute) { if (ATTRIBUTES.contains(attribute)) { return file.getAttribute("dos", attribute); } return null; } @Override public void set(File file, String view, String attribute, Object value, boolean create) { if (supports(attribute)) { checkNotCreate(view, attribute, create); file.setAttribute("dos", attribute, checkType(view, attribute, value, Boolean.class)); } } @Override public Class<DosFileAttributeView> viewType() { return DosFileAttributeView.class; } @Override public DosFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View(lookup, (BasicFileAttributeView) inheritedViews.get("basic")); } @Override public Class<DosFileAttributes> attributesType() { return DosFileAttributes.class; } @Override public DosFileAttributes readAttributes(File file) { return new Attributes(file); } /** Implementation of {@link DosFileAttributeView}. */ private static final class View extends AbstractAttributeView implements DosFileAttributeView { private final BasicFileAttributeView basicView; public View(FileLookup lookup, BasicFileAttributeView basicView) { super(lookup); this.basicView = checkNotNull(basicView); } @Override public String name() { return "dos"; } @Override public DosFileAttributes readAttributes() throws IOException { return new Attributes(lookupFile()); } @Override public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException { basicView.setTimes(lastModifiedTime, lastAccessTime, createTime); } @Override public void setReadOnly(boolean value) throws IOException { lookupFile().setAttribute("dos", "readonly", value); } @Override public void setHidden(boolean value) throws IOException { lookupFile().setAttribute("dos", "hidden", value); } @Override public void setSystem(boolean value) throws IOException { lookupFile().setAttribute("dos", "system", value); } @Override public void setArchive(boolean value) throws IOException { lookupFile().setAttribute("dos", "archive", value); } } /** Implementation of {@link DosFileAttributes}. */ static class Attributes extends BasicAttributeProvider.Attributes implements DosFileAttributes { private final boolean readOnly; private final boolean hidden; private final boolean archive; private final boolean system; protected Attributes(File file) { super(file); this.readOnly = (boolean) file.getAttribute("dos", "readonly"); this.hidden = (boolean) file.getAttribute("dos", "hidden"); this.archive = (boolean) file.getAttribute("dos", "archive"); this.system = (boolean) file.getAttribute("dos", "system"); } @Override public boolean isReadOnly() { return readOnly; } @Override public boolean isHidden() { return hidden; } @Override public boolean isArchive() { return archive; } @Override public boolean isSystem() { return system; } } }
return ImmutableMap.of( "dos:readonly", getDefaultValue("dos:readonly", userProvidedDefaults), "dos:hidden", getDefaultValue("dos:hidden", userProvidedDefaults), "dos:archive", getDefaultValue("dos:archive", userProvidedDefaults), "dos:system", getDefaultValue("dos:system", userProvidedDefaults));
1,199
98
1,297
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/File.java
File
isRootDirectory
class File { private final int id; private int links; private FileTime creationTime; private FileTime lastAccessTime; private FileTime lastModifiedTime; // null when only the basic view is used (default) private @Nullable Table<String, String, Object> attributes; File(int id, FileTime creationTime) { this.id = id; this.creationTime = creationTime; this.lastAccessTime = creationTime; this.lastModifiedTime = creationTime; } /** Returns the ID of this file. */ public int id() { return id; } /** * Returns the size, in bytes, of this file's content. Directories and symbolic links have a size * of 0. */ public long size() { return 0; } /** Returns whether or not this file is a directory. */ public final boolean isDirectory() { return this instanceof Directory; } /** Returns whether or not this file is a regular file. */ public final boolean isRegularFile() { return this instanceof RegularFile; } /** Returns whether or not this file is a symbolic link. */ public final boolean isSymbolicLink() { return this instanceof SymbolicLink; } /** * Creates a new file of the same type as this file with the given ID and creation time. Does not * copy the content of this file unless the cost of copying the content is minimal. This is * because this method is called with a hold on the file system's lock. */ abstract File copyWithoutContent(int id, FileTime creationTime); /** * Copies the content of this file to the given file. The given file must be the same type of file * as this file and should have no content. * * <p>This method is used for copying the content of a file after copying the file itself. Does * nothing by default. */ void copyContentTo(File file) throws IOException {} /** * Returns the read-write lock for this file's content, or {@code null} if there is no content * lock. */ @Nullable ReadWriteLock contentLock() { return null; } /** Called when a stream or channel to this file is opened. */ void opened() {} /** * Called when a stream or channel to this file is closed. If there are no more streams or * channels open to the file and it has been deleted, its contents may be deleted. */ void closed() {} /** * Called when (a single link to) this file is deleted. There may be links remaining. Does nothing * by default. */ void deleted() {} /** Returns whether or not this file is a root directory of the file system. */ final boolean isRootDirectory() {<FILL_FUNCTION_BODY>} /** Returns the current count of links to this file. */ public final synchronized int links() { return links; } /** * Called when this file has been linked in a directory. The given entry is the new directory * entry that links to this file. */ void linked(DirectoryEntry entry) { checkNotNull(entry); } /** Called when this file has been unlinked from a directory, either for a move or delete. */ void unlinked() {} /** Increments the link count for this file. */ final synchronized void incrementLinkCount() { links++; } /** Decrements the link count for this file. */ final synchronized void decrementLinkCount() { links--; } /** Gets the creation time of the file. */ public final synchronized FileTime getCreationTime() { return creationTime; } /** Gets the last access time of the file. */ public final synchronized FileTime getLastAccessTime() { return lastAccessTime; } /** Gets the last modified time of the file. */ public final synchronized FileTime getLastModifiedTime() { return lastModifiedTime; } /** Sets the creation time of the file. */ final synchronized void setCreationTime(FileTime creationTime) { this.creationTime = creationTime; } /** Sets the last access time of the file. */ final synchronized void setLastAccessTime(FileTime lastAccessTime) { this.lastAccessTime = lastAccessTime; } /** Sets the last modified time of the file. */ final synchronized void setLastModifiedTime(FileTime lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } /** * Returns the names of the attributes contained in the given attribute view in the file's * attributes table. */ public final synchronized ImmutableSet<String> getAttributeNames(String view) { if (attributes == null) { return ImmutableSet.of(); } return ImmutableSet.copyOf(attributes.row(view).keySet()); } /** Returns the attribute keys contained in the attributes map for the file. */ @VisibleForTesting final synchronized ImmutableSet<String> getAttributeKeys() { if (attributes == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for (Table.Cell<String, String, Object> cell : attributes.cellSet()) { builder.add(cell.getRowKey() + ':' + cell.getColumnKey()); } return builder.build(); } /** Gets the value of the given attribute in the given view. */ public final synchronized @Nullable Object getAttribute(String view, String attribute) { if (attributes == null) { return null; } return attributes.get(view, attribute); } /** Sets the given attribute in the given view to the given value. */ public final synchronized void setAttribute(String view, String attribute, Object value) { if (attributes == null) { attributes = HashBasedTable.create(); } attributes.put(view, attribute, value); } /** Deletes the given attribute from the given view. */ public final synchronized void deleteAttribute(String view, String attribute) { if (attributes != null) { attributes.remove(view, attribute); } } /** Copies basic attributes (file times) from this file to the given file. */ final synchronized void copyBasicAttributes(File target) { target.setFileTimes(creationTime, lastModifiedTime, lastAccessTime); } private synchronized void setFileTimes( FileTime creationTime, FileTime lastModifiedTime, FileTime lastAccessTime) { this.creationTime = creationTime; this.lastModifiedTime = lastModifiedTime; this.lastAccessTime = lastAccessTime; } /** Copies the attributes from this file to the given file. */ final synchronized void copyAttributes(File target) { copyBasicAttributes(target); target.putAll(attributes); } private synchronized void putAll(@Nullable Table<String, String, Object> attributes) { if (attributes != null && this.attributes != attributes) { if (this.attributes == null) { this.attributes = HashBasedTable.create(); } this.attributes.putAll(attributes); } } @Override public final String toString() { return MoreObjects.toStringHelper(this).add("id", id()).toString(); } }
// only root directories have their parent link pointing to themselves return isDirectory() && equals(((Directory) this).parent());
1,915
32
1,947
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/FileSystemState.java
FileSystemState
register
class FileSystemState implements Closeable { private final Set<Closeable> resources = Sets.newConcurrentHashSet(); private final FileTimeSource fileTimeSource; private final Runnable onClose; private final AtomicBoolean open = new AtomicBoolean(true); /** Count of resources currently in the process of being registered. */ private final AtomicInteger registering = new AtomicInteger(); FileSystemState(FileTimeSource fileTimeSource, Runnable onClose) { this.fileTimeSource = checkNotNull(fileTimeSource); this.onClose = checkNotNull(onClose); } /** Returns whether or not the file system is open. */ public boolean isOpen() { return open.get(); } /** * Checks that the file system is open, throwing {@link ClosedFileSystemException} if it is not. */ public void checkOpen() { if (!open.get()) { throw new ClosedFileSystemException(); } } /** * Registers the given resource to be closed when the file system is closed. Should be called when * the resource is opened. */ @CanIgnoreReturnValue public <C extends Closeable> C register(C resource) {<FILL_FUNCTION_BODY>} /** Unregisters the given resource. Should be called when the resource is closed. */ public void unregister(Closeable resource) { resources.remove(resource); } /** Returns the current {@link FileTime}. */ public FileTime now() { return fileTimeSource.now(); } /** * Closes the file system, runs the {@code onClose} callback and closes all registered resources. */ @Override public void close() throws IOException { if (open.compareAndSet(true, false)) { onClose.run(); Throwable thrown = null; do { for (Closeable resource : resources) { try { resource.close(); } catch (Throwable e) { if (thrown == null) { thrown = e; } else { thrown.addSuppressed(e); } } finally { // ensure the resource is removed even if it doesn't remove itself when closed resources.remove(resource); } } // It's possible for a thread registering a resource to register that resource after open // has been set to false and even after we've looped through and closed all the resources. // Since registering must be incremented *before* checking the state of open, however, // when we reach this point in that situation either the register call is still in progress // (registering > 0) or the new resource has been successfully added (resources not empty). // In either case, we just need to repeat the loop until there are no more register calls // in progress (no new calls can start and no resources left to close. } while (registering.get() > 0 || !resources.isEmpty()); if (thrown != null) { throwIfInstanceOf(thrown, IOException.class); throwIfUnchecked(thrown); } } } }
// Initial open check to avoid incrementing registering if we already know it's closed. // This is to prevent any possibility of a weird pathalogical situation where the do/while // loop in close() keeps looping as register() is called repeatedly from multiple threads. checkOpen(); registering.incrementAndGet(); try { // Need to check again after marking registration in progress to avoid a potential race. // (close() could have run completely between the first checkOpen() and // registering.incrementAndGet().) checkOpen(); resources.add(resource); return resource; } finally { registering.decrementAndGet(); }
790
170
960
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/FileTree.java
FileTree
lookUp
class FileTree { /** * Doesn't much matter, but this number comes from MIN_ELOOP_THRESHOLD <a * href="https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob_plain;f=sysdeps/generic/eloop-threshold.h;hb=HEAD"> * here</a> */ private static final int MAX_SYMBOLIC_LINK_DEPTH = 40; private static final ImmutableList<Name> EMPTY_PATH_NAMES = ImmutableList.of(Name.SELF); /** Map of root names to root directories. */ private final ImmutableSortedMap<Name, Directory> roots; /** Creates a new file tree with the given root directories. */ FileTree(Map<Name, Directory> roots) { this.roots = ImmutableSortedMap.copyOf(roots, Name.canonicalOrdering()); } /** Returns the names of the root directories in this tree. */ public ImmutableSortedSet<Name> getRootDirectoryNames() { return roots.keySet(); } /** * Gets the directory entry for the root with the given name or {@code null} if no such root * exists. */ public @Nullable DirectoryEntry getRoot(Name name) { Directory dir = roots.get(name); return dir == null ? null : dir.entryInParent(); } /** Returns the result of the file lookup for the given path. */ public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path did not exist or was not a directory throw new NoSuchFileException(path.toString()); } return result; } private @Nullable DirectoryEntry lookUp( File dir, JimfsPath path, Set<? super LinkOption> options, int linkDepth) throws IOException {<FILL_FUNCTION_BODY>} /** * Looks up the given names against the given base file. If the file is not a directory, the * lookup fails. */ private @Nullable DirectoryEntry lookUp( File dir, Iterable<Name> names, Set<? super LinkOption> options, int linkDepth) throws IOException { Iterator<Name> nameIterator = names.iterator(); Name name = nameIterator.next(); while (nameIterator.hasNext()) { Directory directory = toDirectory(dir); if (directory == null) { return null; } DirectoryEntry entry = directory.get(name); if (entry == null) { return null; } File file = entry.file(); if (file.isSymbolicLink()) { DirectoryEntry linkResult = followSymbolicLink(dir, (SymbolicLink) file, linkDepth); if (linkResult == null) { return null; } dir = linkResult.fileOrNull(); } else { dir = file; } name = nameIterator.next(); } return lookUpLast(dir, name, options, linkDepth); } /** Looks up the last element of a path. */ private @Nullable DirectoryEntry lookUpLast( @Nullable File dir, Name name, Set<? super LinkOption> options, int linkDepth) throws IOException { Directory directory = toDirectory(dir); if (directory == null) { return null; } DirectoryEntry entry = directory.get(name); if (entry == null) { return new DirectoryEntry(directory, name, null); } File file = entry.file(); if (!options.contains(LinkOption.NOFOLLOW_LINKS) && file.isSymbolicLink()) { return followSymbolicLink(dir, (SymbolicLink) file, linkDepth); } return getRealEntry(entry); } /** * Returns the directory entry located by the target path of the given symbolic link, resolved * relative to the given directory. */ private @Nullable DirectoryEntry followSymbolicLink(File dir, SymbolicLink link, int linkDepth) throws IOException { if (linkDepth >= MAX_SYMBOLIC_LINK_DEPTH) { throw new IOException("too many levels of symbolic links"); } return lookUp(dir, link.target(), Options.FOLLOW_LINKS, linkDepth + 1); } /** * Returns the entry for the file in its parent directory. This will be the given entry unless the * name for the entry is "." or "..", in which the directory linking to the file is not the file's * parent directory. In that case, we know the file must be a directory ("." and ".." can only * link to directories), so we can just get the entry in the directory's parent directory that * links to it. So, for example, if we have a directory "foo" that contains a directory "bar" and * we find an entry [bar -> "." -> bar], we instead return the entry for bar in its parent, [foo * -> "bar" -> bar]. */ private @Nullable DirectoryEntry getRealEntry(DirectoryEntry entry) { Name name = entry.name(); if (name.equals(Name.SELF) || name.equals(Name.PARENT)) { Directory dir = toDirectory(entry.file()); assert dir != null; return dir.entryInParent(); } else { return entry; } } private @Nullable Directory toDirectory(@Nullable File file) { return file == null || !file.isDirectory() ? null : (Directory) file; } private static boolean isEmpty(ImmutableList<Name> names) { // the empty path (created by FileSystem.getPath("")), has no root and a single name, "" return names.isEmpty() || (names.size() == 1 && names.get(0).toString().isEmpty()); } }
ImmutableList<Name> names = path.names(); if (path.isAbsolute()) { // look up the root directory DirectoryEntry entry = getRoot(path.root()); if (entry == null) { // root not found; always return null as no real parent directory exists // this prevents new roots from being created in file systems supporting multiple roots return null; } else if (names.isEmpty()) { // root found, no more names to look up return entry; } else { // root found, more names to look up; set dir to the root directory for the path dir = entry.file(); } } else if (isEmpty(names)) { // set names to the canonical list of names for an empty path (singleton list of ".") names = EMPTY_PATH_NAMES; } return lookUp(dir, names, options, linkDepth);
1,555
226
1,781
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/Handler.java
Handler
register
class Handler extends URLStreamHandler { private static final String JAVA_PROTOCOL_HANDLER_PACKAGES = "java.protocol.handler.pkgs"; /** * Registers this handler by adding the package {@code com.google.common} to the system property * {@code "java.protocol.handler.pkgs"}. Java will then look for this class in the {@code jimfs} * (the name of the protocol) package of {@code com.google.common}. * * @throws SecurityException if the system property that needs to be set to register this handler * can't be read or written. */ static void register() { register(Handler.class); } /** Generic method that would allow registration of any properly placed {@code Handler} class. */ static void register(Class<? extends URLStreamHandler> handlerClass) {<FILL_FUNCTION_BODY>} /** @deprecated Not intended to be called directly; this class is only for use by Java itself. */ @Deprecated public Handler() {} // a public, no-arg constructor is required @Override protected URLConnection openConnection(URL url) throws IOException { return new PathURLConnection(url); } @Override @SuppressWarnings("UnsynchronizedOverridesSynchronized") // no need to synchronize to return null protected @Nullable InetAddress getHostAddress(URL url) { // jimfs uses the URI host to specify the name of the file system being used. // In the default implementation of getHostAddress(URL), a non-null host would cause an attempt // to look up the IP address, causing a slowdown on calling equals/hashCode methods on the URL // object. By returning null, we speed up equality checks on URL's (since there isn't an IP to // connect to). return null; } }
checkArgument("Handler".equals(handlerClass.getSimpleName())); String pkg = handlerClass.getPackage().getName(); int lastDot = pkg.lastIndexOf('.'); checkArgument(lastDot > 0, "package for Handler (%s) must have a parent package", pkg); String parentPackage = pkg.substring(0, lastDot); String packages = System.getProperty(JAVA_PROTOCOL_HANDLER_PACKAGES); if (packages == null) { packages = parentPackage; } else { packages += "|" + parentPackage; } System.setProperty(JAVA_PROTOCOL_HANDLER_PACKAGES, packages);
470
188
658
<methods>public void <init>() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/HeapDisk.java
HeapDisk
allocate
class HeapDisk { /** Fixed size of each block for this disk. */ private final int blockSize; /** Maximum total number of blocks that the disk may contain at any time. */ private final int maxBlockCount; /** Maximum total number of unused blocks that may be cached for reuse at any time. */ private final int maxCachedBlockCount; /** * Cache of free blocks to be allocated to files. While this is stored as a file, it isn't used * like a normal file: only the methods for accessing its blocks are used. */ @VisibleForTesting final RegularFile blockCache; /** The current total number of blocks that are currently allocated to files. */ private int allocatedBlockCount; /** Creates a new disk using settings from the given configuration. */ public HeapDisk(Configuration config) { this.blockSize = config.blockSize; this.maxBlockCount = toBlockCount(config.maxSize, blockSize); this.maxCachedBlockCount = config.maxCacheSize == -1 ? maxBlockCount : toBlockCount(config.maxCacheSize, blockSize); this.blockCache = createBlockCache(maxCachedBlockCount); } /** * Creates a new disk with the given {@code blockSize}, {@code maxBlockCount} and {@code * maxCachedBlockCount}. */ public HeapDisk(int blockSize, int maxBlockCount, int maxCachedBlockCount) { checkArgument(blockSize > 0, "blockSize (%s) must be positive", blockSize); checkArgument(maxBlockCount > 0, "maxBlockCount (%s) must be positive", maxBlockCount); checkArgument( maxCachedBlockCount >= 0, "maxCachedBlockCount (%s) must be non-negative", maxCachedBlockCount); this.blockSize = blockSize; this.maxBlockCount = maxBlockCount; this.maxCachedBlockCount = maxCachedBlockCount; this.blockCache = createBlockCache(maxCachedBlockCount); } /** Returns the nearest multiple of {@code blockSize} that is <= {@code size}. */ private static int toBlockCount(long size, int blockSize) { return (int) LongMath.divide(size, blockSize, RoundingMode.FLOOR); } private RegularFile createBlockCache(int maxCachedBlockCount) { // This file is just for holding blocks so things like the creation time don't matter return new RegularFile( -1, SystemFileTimeSource.INSTANCE.now(), this, new byte[Math.min(maxCachedBlockCount, 8192)][], 0, 0); } /** Returns the size of blocks created by this disk. */ public int blockSize() { return blockSize; } /** * Returns the total size of this disk. This is the maximum size of the disk and does not reflect * the amount of data currently allocated or cached. */ public synchronized long getTotalSpace() { return maxBlockCount * (long) blockSize; } /** * Returns the current number of unallocated bytes on this disk. This is the maximum number of * additional bytes that could be allocated and does not reflect the number of bytes currently * actually cached in the disk. */ public synchronized long getUnallocatedSpace() { return (maxBlockCount - allocatedBlockCount) * (long) blockSize; } /** Allocates the given number of blocks and adds them to the given file. */ public synchronized void allocate(RegularFile file, int count) throws IOException {<FILL_FUNCTION_BODY>} /** Frees all blocks in the given file. */ public void free(RegularFile file) { free(file, file.blockCount()); } /** Frees the last {@code count} blocks from the given file. */ public synchronized void free(RegularFile file, int count) { int remainingCacheSpace = maxCachedBlockCount - blockCache.blockCount(); if (remainingCacheSpace > 0) { file.copyBlocksTo(blockCache, Math.min(count, remainingCacheSpace)); } file.truncateBlocks(file.blockCount() - count); allocatedBlockCount -= count; } }
int newAllocatedBlockCount = allocatedBlockCount + count; if (newAllocatedBlockCount > maxBlockCount) { throw new IOException("out of disk space"); } int newBlocksNeeded = Math.max(count - blockCache.blockCount(), 0); for (int i = 0; i < newBlocksNeeded; i++) { file.addBlock(new byte[blockSize]); } if (newBlocksNeeded != count) { blockCache.transferBlocksTo(file, count - newBlocksNeeded); } allocatedBlockCount = newAllocatedBlockCount;
1,092
162
1,254
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsAsynchronousFileChannel.java
CompletionHandlerCallback
run
class CompletionHandlerCallback<R, A> implements Runnable { private final ListenableFuture<R> future; private final CompletionHandler<R, ? super A> completionHandler; private final @Nullable A attachment; private CompletionHandlerCallback( ListenableFuture<R> future, CompletionHandler<R, ? super A> completionHandler, @Nullable A attachment) { this.future = checkNotNull(future); this.completionHandler = checkNotNull(completionHandler); this.attachment = attachment; } @Override public void run() {<FILL_FUNCTION_BODY>} private void onSuccess(R result) { completionHandler.completed(result, attachment); } private void onFailure(Throwable t) { completionHandler.failed(t, attachment); } }
R result; try { result = Futures.getDone(future); } catch (ExecutionException e) { onFailure(e.getCause()); return; } catch (RuntimeException | Error e) { onFailure(e); return; } onSuccess(result);
216
83
299
<methods>public abstract void force(boolean) throws java.io.IOException,public final Future<java.nio.channels.FileLock> lock() ,public final void lock(A, CompletionHandler<java.nio.channels.FileLock,? super A>) ,public abstract Future<java.nio.channels.FileLock> lock(long, long, boolean) ,public abstract void lock(long, long, boolean, A, CompletionHandler<java.nio.channels.FileLock,? super A>) ,public static transient java.nio.channels.AsynchronousFileChannel open(java.nio.file.Path, java.nio.file.OpenOption[]) throws java.io.IOException,public static transient java.nio.channels.AsynchronousFileChannel open(java.nio.file.Path, Set<? extends java.nio.file.OpenOption>, java.util.concurrent.ExecutorService, FileAttribute<?>[]) throws java.io.IOException,public abstract Future<java.lang.Integer> read(java.nio.ByteBuffer, long) ,public abstract void read(java.nio.ByteBuffer, long, A, CompletionHandler<java.lang.Integer,? super A>) ,public abstract long size() throws java.io.IOException,public abstract java.nio.channels.AsynchronousFileChannel truncate(long) throws java.io.IOException,public final java.nio.channels.FileLock tryLock() throws java.io.IOException,public abstract java.nio.channels.FileLock tryLock(long, long, boolean) throws java.io.IOException,public abstract Future<java.lang.Integer> write(java.nio.ByteBuffer, long) ,public abstract void write(java.nio.ByteBuffer, long, A, CompletionHandler<java.lang.Integer,? super A>) <variables>private static final FileAttribute<?>[] NO_ATTRIBUTES
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsFileSystem.java
JimfsFileSystem
getRootDirectories
class JimfsFileSystem extends FileSystem { private final JimfsFileSystemProvider provider; private final URI uri; private final JimfsFileStore fileStore; private final PathService pathService; private final UserPrincipalLookupService userLookupService = new UserLookupService(true); private final FileSystemView defaultView; private final WatchServiceConfiguration watchServiceConfig; JimfsFileSystem( JimfsFileSystemProvider provider, URI uri, JimfsFileStore fileStore, PathService pathService, FileSystemView defaultView, WatchServiceConfiguration watchServiceConfig) { this.provider = checkNotNull(provider); this.uri = checkNotNull(uri); this.fileStore = checkNotNull(fileStore); this.pathService = checkNotNull(pathService); this.defaultView = checkNotNull(defaultView); this.watchServiceConfig = checkNotNull(watchServiceConfig); } @Override public JimfsFileSystemProvider provider() { return provider; } /** Returns the URI for this file system. */ public URI getUri() { return uri; } /** Returns the default view for this file system. */ public FileSystemView getDefaultView() { return defaultView; } @Override public String getSeparator() { return pathService.getSeparator(); } @SuppressWarnings("unchecked") // safe cast of immutable set @Override public ImmutableSortedSet<Path> getRootDirectories() {<FILL_FUNCTION_BODY>} /** Returns the working directory path for this file system. */ public JimfsPath getWorkingDirectory() { return defaultView.getWorkingDirectoryPath(); } /** Returns the path service for this file system. */ @VisibleForTesting PathService getPathService() { return pathService; } /** Returns the file store for this file system. */ public JimfsFileStore getFileStore() { return fileStore; } @Override public ImmutableSet<FileStore> getFileStores() { fileStore.state().checkOpen(); return ImmutableSet.<FileStore>of(fileStore); } @Override public ImmutableSet<String> supportedFileAttributeViews() { return fileStore.supportedFileAttributeViews(); } @Override public JimfsPath getPath(String first, String... more) { fileStore.state().checkOpen(); return pathService.parsePath(first, more); } /** Gets the URI of the given path in this file system. */ public URI toUri(JimfsPath path) { fileStore.state().checkOpen(); return pathService.toUri(uri, path.toAbsolutePath()); } /** Converts the given URI into a path in this file system. */ public JimfsPath toPath(URI uri) { fileStore.state().checkOpen(); return pathService.fromUri(uri); } @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { fileStore.state().checkOpen(); return pathService.createPathMatcher(syntaxAndPattern); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { fileStore.state().checkOpen(); return userLookupService; } @Override public WatchService newWatchService() throws IOException { return watchServiceConfig.newWatchService(defaultView, pathService); } private @Nullable ExecutorService defaultThreadPool; /** * Returns a default thread pool to use for asynchronous file channels when users do not provide * an executor themselves. (This is required by the spec of newAsynchronousFileChannel in * FileSystemProvider.) */ public synchronized ExecutorService getDefaultThreadPool() { if (defaultThreadPool == null) { defaultThreadPool = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("JimfsFileSystem-" + uri.getHost() + "-defaultThreadPool-%s") .build()); // ensure thread pool is closed when file system is closed fileStore .state() .register( new Closeable() { @Override public void close() { defaultThreadPool.shutdown(); } }); } return defaultThreadPool; } /** * Returns {@code false}; currently, cannot create a read-only file system. * * @return {@code false}, always */ @Override public boolean isReadOnly() { return false; } @Override public boolean isOpen() { return fileStore.state().isOpen(); } @Override public void close() throws IOException { fileStore.state().close(); } }
ImmutableSortedSet.Builder<JimfsPath> builder = ImmutableSortedSet.orderedBy(pathService); for (Name name : fileStore.getRootDirectoryNames()) { builder.add(pathService.createRoot(name)); } return (ImmutableSortedSet<Path>) (ImmutableSortedSet<?>) builder.build();
1,249
92
1,341
<methods>public abstract void close() throws java.io.IOException,public abstract Iterable<java.nio.file.FileStore> getFileStores() ,public transient abstract java.nio.file.Path getPath(java.lang.String, java.lang.String[]) ,public abstract java.nio.file.PathMatcher getPathMatcher(java.lang.String) ,public abstract Iterable<java.nio.file.Path> getRootDirectories() ,public abstract java.lang.String getSeparator() ,public abstract java.nio.file.attribute.UserPrincipalLookupService getUserPrincipalLookupService() ,public abstract boolean isOpen() ,public abstract boolean isReadOnly() ,public abstract java.nio.file.WatchService newWatchService() throws java.io.IOException,public abstract java.nio.file.spi.FileSystemProvider provider() ,public abstract Set<java.lang.String> supportedFileAttributeViews() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsFileSystems.java
JimfsFileSystems
createFileStore
class JimfsFileSystems { private JimfsFileSystems() {} private static final Runnable DO_NOTHING = new Runnable() { @Override public void run() {} }; /** * Returns a {@code Runnable} that will remove the file system with the given {@code URI} from the * system provider's cache when called. */ private static Runnable removeFileSystemRunnable(URI uri) { if (Jimfs.systemProvider == null) { // TODO(cgdecker): Use Runnables.doNothing() when it's out of @Beta return DO_NOTHING; } // We have to invoke the SystemJimfsFileSystemProvider.removeFileSystemRunnable(URI) // method reflectively since the system-loaded instance of it may be a different class // than the one we'd get if we tried to cast it and call it like normal here. try { Method method = Jimfs.systemProvider.getClass().getDeclaredMethod("removeFileSystemRunnable", URI.class); return (Runnable) method.invoke(null, uri); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException( "Unable to get Runnable for removing the FileSystem from the cache when it is closed", e); } } /** * Initialize and configure a new file system with the given provider and URI, using the given * configuration. */ public static JimfsFileSystem newFileSystem( JimfsFileSystemProvider provider, URI uri, Configuration config) throws IOException { PathService pathService = new PathService(config); FileSystemState state = new FileSystemState(config.fileTimeSource, removeFileSystemRunnable(uri)); JimfsFileStore fileStore = createFileStore(config, pathService, state); FileSystemView defaultView = createDefaultView(config, fileStore, pathService); WatchServiceConfiguration watchServiceConfig = config.watchServiceConfig; JimfsFileSystem fileSystem = new JimfsFileSystem(provider, uri, fileStore, pathService, defaultView, watchServiceConfig); pathService.setFileSystem(fileSystem); return fileSystem; } /** Creates the file store for the file system. */ private static JimfsFileStore createFileStore( Configuration config, PathService pathService, FileSystemState state) {<FILL_FUNCTION_BODY>} /** Creates the default view of the file system using the given working directory. */ private static FileSystemView createDefaultView( Configuration config, JimfsFileStore fileStore, PathService pathService) throws IOException { JimfsPath workingDirPath = pathService.parsePath(config.workingDirectory); Directory dir = fileStore.getRoot(workingDirPath.root()); if (dir == null) { throw new IllegalArgumentException("Invalid working dir path: " + workingDirPath); } for (Name name : workingDirPath.names()) { Directory newDir = fileStore.directoryCreator().get(); fileStore.setInitialAttributes(newDir); dir.link(name, newDir); dir = newDir; } return new FileSystemView(fileStore, dir, workingDirPath); } }
AttributeService attributeService = new AttributeService(config); HeapDisk disk = new HeapDisk(config); FileFactory fileFactory = new FileFactory(disk, config.fileTimeSource); Map<Name, Directory> roots = new HashMap<>(); // create roots for (String root : config.roots) { JimfsPath path = pathService.parsePath(root); if (!path.isAbsolute() && path.getNameCount() == 0) { throw new IllegalArgumentException("Invalid root path: " + root); } Name rootName = path.root(); Directory rootDir = fileFactory.createRootDirectory(rootName); attributeService.setInitialAttributes(rootDir); roots.put(rootName, rootDir); } return new JimfsFileStore( new FileTree(roots), fileFactory, disk, attributeService, config.supportedFeatures, state);
829
229
1,058
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsInputStream.java
JimfsInputStream
readInternal
class JimfsInputStream extends InputStream { @GuardedBy("this") @VisibleForTesting RegularFile file; @GuardedBy("this") private long pos; @GuardedBy("this") private boolean finished; private final FileSystemState fileSystemState; public JimfsInputStream(RegularFile file, FileSystemState fileSystemState) { this.file = checkNotNull(file); this.fileSystemState = fileSystemState; fileSystemState.register(this); } @Override public synchronized int read() throws IOException { checkNotClosed(); if (finished) { return -1; } file.readLock().lock(); try { int b = file.read(pos++); // it's ok for pos to go beyond size() if (b == -1) { finished = true; } else { file.setLastAccessTime(fileSystemState.now()); } return b; } finally { file.readLock().unlock(); } } @Override public int read(byte[] b) throws IOException { return readInternal(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { checkPositionIndexes(off, off + len, b.length); return readInternal(b, off, len); } private synchronized int readInternal(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} @Override public long skip(long n) throws IOException { if (n <= 0) { return 0; } synchronized (this) { checkNotClosed(); if (finished) { return 0; } // available() must be an int, so the min must be also int skip = (int) Math.min(Math.max(file.size() - pos, 0), n); pos += skip; return skip; } } @Override public synchronized int available() throws IOException { checkNotClosed(); if (finished) { return 0; } long available = Math.max(file.size() - pos, 0); return Ints.saturatedCast(available); } @GuardedBy("this") private void checkNotClosed() throws IOException { if (file == null) { throw new IOException("stream is closed"); } } @Override public synchronized void close() throws IOException { if (isOpen()) { fileSystemState.unregister(this); file.closed(); // file is set to null here and only here file = null; } } @GuardedBy("this") private boolean isOpen() { return file != null; } }
checkNotClosed(); if (finished) { return -1; } file.readLock().lock(); try { int read = file.read(pos, b, off, len); if (read == -1) { finished = true; } else { pos += read; } file.setLastAccessTime(fileSystemState.now()); return read; } finally { file.readLock().unlock(); }
750
125
875
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsOutputStream.java
JimfsOutputStream
writeInternal
class JimfsOutputStream extends OutputStream { @GuardedBy("this") @VisibleForTesting RegularFile file; @GuardedBy("this") private long pos; private final boolean append; private final FileSystemState fileSystemState; JimfsOutputStream(RegularFile file, boolean append, FileSystemState fileSystemState) { this.file = checkNotNull(file); this.append = append; this.fileSystemState = fileSystemState; fileSystemState.register(this); } @Override public synchronized void write(int b) throws IOException { checkNotClosed(); file.writeLock().lock(); try { if (append) { pos = file.sizeWithoutLocking(); } file.write(pos++, (byte) b); file.setLastModifiedTime(fileSystemState.now()); } finally { file.writeLock().unlock(); } } @Override public void write(byte[] b) throws IOException { writeInternal(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { checkPositionIndexes(off, off + len, b.length); writeInternal(b, off, len); } private synchronized void writeInternal(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} @GuardedBy("this") private void checkNotClosed() throws IOException { if (file == null) { throw new IOException("stream is closed"); } } @Override public synchronized void close() throws IOException { if (isOpen()) { fileSystemState.unregister(this); file.closed(); // file is set to null here and only here file = null; } } @GuardedBy("this") private boolean isOpen() { return file != null; } }
checkNotClosed(); file.writeLock().lock(); try { if (append) { pos = file.sizeWithoutLocking(); } pos += file.write(pos, b, off, len); file.setLastModifiedTime(fileSystemState.now()); } finally { file.writeLock().unlock(); }
516
95
611
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/JimfsSecureDirectoryStream.java
DirectoryIterator
lookup
class DirectoryIterator extends AbstractIterator<Path> { private @Nullable Iterator<Name> fileNames; @Override protected synchronized Path computeNext() { checkOpen(); try { if (fileNames == null) { fileNames = view.snapshotWorkingDirectoryEntries().iterator(); } while (fileNames.hasNext()) { Name name = fileNames.next(); Path path = view.getWorkingDirectoryPath().resolve(name); if (filter.accept(path)) { return path; } } return endOfData(); } catch (IOException e) { throw new DirectoryIteratorException(e); } } } /** A stream filter that always returns true. */ public static final Filter<Object> ALWAYS_TRUE_FILTER = new Filter<Object>() { @Override public boolean accept(Object entry) throws IOException { return true; } }; @Override public SecureDirectoryStream<Path> newDirectoryStream(Path path, LinkOption... options) throws IOException { checkOpen(); JimfsPath checkedPath = checkPath(path); // safe cast because a file system that supports SecureDirectoryStream always creates // SecureDirectoryStreams return (SecureDirectoryStream<Path>) view.newDirectoryStream( checkedPath, ALWAYS_TRUE_FILTER, Options.getLinkOptions(options), path().resolve(checkedPath)); } @Override public SeekableByteChannel newByteChannel( Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { checkOpen(); JimfsPath checkedPath = checkPath(path); ImmutableSet<OpenOption> opts = Options.getOptionsForChannel(options); return new JimfsFileChannel( view.getOrCreateRegularFile(checkedPath, opts), opts, fileSystemState); } @Override public void deleteFile(Path path) throws IOException { checkOpen(); JimfsPath checkedPath = checkPath(path); view.deleteFile(checkedPath, FileSystemView.DeleteMode.NON_DIRECTORY_ONLY); } @Override public void deleteDirectory(Path path) throws IOException { checkOpen(); JimfsPath checkedPath = checkPath(path); view.deleteFile(checkedPath, FileSystemView.DeleteMode.DIRECTORY_ONLY); } @Override public void move(Path srcPath, SecureDirectoryStream<Path> targetDir, Path targetPath) throws IOException { checkOpen(); JimfsPath checkedSrcPath = checkPath(srcPath); JimfsPath checkedTargetPath = checkPath(targetPath); if (!(targetDir instanceof JimfsSecureDirectoryStream)) { throw new ProviderMismatchException( "targetDir isn't a secure directory stream associated with this file system"); } JimfsSecureDirectoryStream checkedTargetDir = (JimfsSecureDirectoryStream) targetDir; view.copy( checkedSrcPath, checkedTargetDir.view, checkedTargetPath, ImmutableSet.<CopyOption>of(), true); } @Override public <V extends FileAttributeView> V getFileAttributeView(Class<V> type) { return getFileAttributeView(path().getFileSystem().getPath("."), type); } @Override public <V extends FileAttributeView> V getFileAttributeView( Path path, Class<V> type, LinkOption... options) { checkOpen(); final JimfsPath checkedPath = checkPath(path); final ImmutableSet<LinkOption> optionsSet = Options.getLinkOptions(options); return view.getFileAttributeView( new FileLookup() { @Override public File lookup() throws IOException {<FILL_FUNCTION_BODY>
checkOpen(); // per the spec, must check that the stream is open for each view operation return view.lookUpWithLock(checkedPath, optionsSet).requireExists(checkedPath).file();
990
48
1,038
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/Name.java
Name
equals
class Name { /** The empty name. */ static final Name EMPTY = new Name("", ""); /** The name to use for a link from a directory to itself. */ public static final Name SELF = new Name(".", "."); /** The name to use for a link from a directory to its parent directory. */ public static final Name PARENT = new Name("..", ".."); /** Creates a new name with no normalization done on the given string. */ @VisibleForTesting static Name simple(String name) { switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } } /** * Creates a name with the given display representation and the given canonical representation. */ public static Name create(String display, String canonical) { return new Name(display, canonical); } private final String display; private final String canonical; private Name(String display, String canonical) { this.display = checkNotNull(display); this.canonical = checkNotNull(canonical); } @Override public boolean equals(@Nullable Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Util.smearHash(canonical.hashCode()); } @Override public String toString() { return display; } /** Returns an ordering that orders names by their display representation. */ public static Ordering<Name> displayOrdering() { return DISPLAY_ORDERING; } /** Returns an ordering that orders names by their canonical representation. */ public static Ordering<Name> canonicalOrdering() { return CANONICAL_ORDERING; } private static final Ordering<Name> DISPLAY_ORDERING = Ordering.natural() .onResultOf( new Function<Name, String>() { @Override public String apply(Name name) { return name.display; } }); private static final Ordering<Name> CANONICAL_ORDERING = Ordering.natural() .onResultOf( new Function<Name, String>() { @Override public String apply(Name name) { return name.canonical; } }); }
if (obj instanceof Name) { Name other = (Name) obj; return canonical.equals(other.canonical); } return false;
603
42
645
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/Options.java
Options
getOptionsForChannel
class Options { private Options() {} /** Immutable set containing LinkOption.NOFOLLOW_LINKS. */ public static final ImmutableSet<LinkOption> NOFOLLOW_LINKS = ImmutableSet.of(LinkOption.NOFOLLOW_LINKS); /** Immutable empty LinkOption set. */ public static final ImmutableSet<LinkOption> FOLLOW_LINKS = ImmutableSet.of(); private static final ImmutableSet<OpenOption> DEFAULT_READ = ImmutableSet.<OpenOption>of(READ); private static final ImmutableSet<OpenOption> DEFAULT_READ_NOFOLLOW_LINKS = ImmutableSet.<OpenOption>of(READ, LinkOption.NOFOLLOW_LINKS); private static final ImmutableSet<OpenOption> DEFAULT_WRITE = ImmutableSet.<OpenOption>of(WRITE, CREATE, TRUNCATE_EXISTING); /** Returns an immutable set of link options. */ public static ImmutableSet<LinkOption> getLinkOptions(LinkOption... options) { return options.length == 0 ? FOLLOW_LINKS : NOFOLLOW_LINKS; } /** Returns an immutable set of open options for opening a new file channel. */ public static ImmutableSet<OpenOption> getOptionsForChannel(Set<? extends OpenOption> options) {<FILL_FUNCTION_BODY>} /** Returns an immutable set of open options for opening a new input stream. */ @SuppressWarnings("unchecked") // safe covariant cast public static ImmutableSet<OpenOption> getOptionsForInputStream(OpenOption... options) { boolean nofollowLinks = false; for (OpenOption option : options) { if (checkNotNull(option) != READ) { if (option == LinkOption.NOFOLLOW_LINKS) { nofollowLinks = true; } else { throw new UnsupportedOperationException("'" + option + "' not allowed"); } } } // just return the link options for finding the file, nothing else is needed return (ImmutableSet<OpenOption>) (ImmutableSet<?>) (nofollowLinks ? NOFOLLOW_LINKS : FOLLOW_LINKS); } /** Returns an immutable set of open options for opening a new output stream. */ public static ImmutableSet<OpenOption> getOptionsForOutputStream(OpenOption... options) { if (options.length == 0) { return DEFAULT_WRITE; } ImmutableSet<OpenOption> result = addWrite(Arrays.asList(options)); if (result.contains(READ)) { throw new UnsupportedOperationException("'READ' not allowed"); } return result; } /** * Returns an {@link ImmutableSet} copy of the given {@code options}, adding {@link * StandardOpenOption#WRITE} if it isn't already present. */ private static ImmutableSet<OpenOption> addWrite(Collection<? extends OpenOption> options) { return options.contains(WRITE) ? ImmutableSet.copyOf(options) : ImmutableSet.<OpenOption>builder().add(WRITE).addAll(options).build(); } /** Returns an immutable set of the given options for a move. */ public static ImmutableSet<CopyOption> getMoveOptions(CopyOption... options) { return ImmutableSet.copyOf(Lists.asList(LinkOption.NOFOLLOW_LINKS, options)); } /** Returns an immutable set of the given options for a copy. */ public static ImmutableSet<CopyOption> getCopyOptions(CopyOption... options) { ImmutableSet<CopyOption> result = ImmutableSet.copyOf(options); if (result.contains(ATOMIC_MOVE)) { throw new UnsupportedOperationException("'ATOMIC_MOVE' not allowed"); } return result; } }
if (options.isEmpty()) { return DEFAULT_READ; } boolean append = options.contains(APPEND); boolean write = append || options.contains(WRITE); boolean read = !write || options.contains(READ); if (read) { if (append) { throw new UnsupportedOperationException("'READ' + 'APPEND' not allowed"); } if (!write) { // ignore all write related options return options.contains(LinkOption.NOFOLLOW_LINKS) ? DEFAULT_READ_NOFOLLOW_LINKS : DEFAULT_READ; } } // options contains write or append and may also contain read // it does not contain both read and append return addWrite(options);
993
195
1,188
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/OwnerAttributeProvider.java
OwnerAttributeProvider
get
class OwnerAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("owner"); private static final UserPrincipal DEFAULT_OWNER = createUserPrincipal("user"); @Override public String name() { return "owner"; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @Override public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) { Object userProvidedOwner = userProvidedDefaults.get("owner:owner"); UserPrincipal owner = DEFAULT_OWNER; if (userProvidedOwner != null) { if (userProvidedOwner instanceof String) { owner = createUserPrincipal((String) userProvidedOwner); } else { throw invalidType("owner", "owner", userProvidedOwner, String.class, UserPrincipal.class); } } return ImmutableMap.of("owner:owner", owner); } @Override public @Nullable Object get(File file, String attribute) {<FILL_FUNCTION_BODY>} @Override public void set(File file, String view, String attribute, Object value, boolean create) { if (attribute.equals("owner")) { checkNotCreate(view, attribute, create); UserPrincipal user = checkType(view, attribute, value, UserPrincipal.class); // TODO(cgdecker): Do we really need to do this? Any reason not to allow any UserPrincipal? if (!(user instanceof UserLookupService.JimfsUserPrincipal)) { user = createUserPrincipal(user.getName()); } file.setAttribute("owner", "owner", user); } } @Override public Class<FileOwnerAttributeView> viewType() { return FileOwnerAttributeView.class; } @Override public FileOwnerAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View(lookup); } /** Implementation of {@link FileOwnerAttributeView}. */ private static final class View extends AbstractAttributeView implements FileOwnerAttributeView { public View(FileLookup lookup) { super(lookup); } @Override public String name() { return "owner"; } @Override public UserPrincipal getOwner() throws IOException { return (UserPrincipal) lookupFile().getAttribute("owner", "owner"); } @Override public void setOwner(UserPrincipal owner) throws IOException { lookupFile().setAttribute("owner", "owner", checkNotNull(owner)); } } }
if (attribute.equals("owner")) { return file.getAttribute("owner", "owner"); } return null;
699
35
734
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/PathMatchers.java
PathMatchers
getPathMatcher
class PathMatchers { private PathMatchers() {} /** * Gets a {@link PathMatcher} for the given syntax and pattern as specified by {@link * FileSystem#getPathMatcher}. The {@code separators} string contains the path name element * separators (one character each) recognized by the file system. For a glob-syntax path matcher, * any of the given separators will be recognized as a separator in the pattern, and any of them * will be matched as a separator when checking a path. */ // TODO(cgdecker): Should I be just canonicalizing separators rather than matching any separator? // Perhaps so, assuming Path always canonicalizes its separators public static PathMatcher getPathMatcher( String syntaxAndPattern, String separators, ImmutableSet<PathNormalization> normalizations) {<FILL_FUNCTION_BODY>} private static PathMatcher fromRegex(String regex, Iterable<PathNormalization> normalizations) { return new RegexPathMatcher(PathNormalization.compilePattern(regex, normalizations)); } /** * {@code PathMatcher} that matches the {@code toString()} form of a {@code Path} against a regex * {@code Pattern}. */ @VisibleForTesting static final class RegexPathMatcher implements PathMatcher { private final Pattern pattern; private RegexPathMatcher(Pattern pattern) { this.pattern = checkNotNull(pattern); } @Override public boolean matches(Path path) { return pattern.matcher(path.toString()).matches(); } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(pattern).toString(); } } }
int syntaxSeparator = syntaxAndPattern.indexOf(':'); checkArgument( syntaxSeparator > 0, "Must be of the form 'syntax:pattern': %s", syntaxAndPattern); String syntax = Ascii.toLowerCase(syntaxAndPattern.substring(0, syntaxSeparator)); String pattern = syntaxAndPattern.substring(syntaxSeparator + 1); switch (syntax) { case "glob": pattern = GlobToRegex.toRegex(pattern, separators); // fall through case "regex": return fromRegex(pattern, normalizations); default: throw new UnsupportedOperationException("Invalid syntax: " + syntaxAndPattern); }
443
179
622
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/PathType.java
PathType
toUri
class PathType { /** * Returns a Unix-style path type. "/" is both the root and the only separator. Any path starting * with "/" is considered absolute. The nul character ('\0') is disallowed in paths. */ public static PathType unix() { return UnixPathType.INSTANCE; } /** * Returns a Windows-style path type. The canonical separator character is "\". "/" is also * treated as a separator when parsing paths. * * <p>As much as possible, this implementation follows the information provided in <a * href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx">this * article</a>. Paths with drive-letter roots (e.g. "C:\") and paths with UNC roots (e.g. * "\\host\share\") are supported. * * <p>Two Windows path features are not currently supported as they are too Windows-specific: * * <ul> * <li>Relative paths containing a drive-letter root, for example "C:" or "C:foo\bar". Such * paths have a root component and optionally have names, but are <i>relative</i> paths, * relative to the working directory of the drive identified by the root. * <li>Absolute paths with no root, for example "\foo\bar". Such paths are absolute paths on the * current drive. * </ul> */ public static PathType windows() { return WindowsPathType.INSTANCE; } private final boolean allowsMultipleRoots; private final String separator; private final String otherSeparators; private final Joiner joiner; private final Splitter splitter; protected PathType(boolean allowsMultipleRoots, char separator, char... otherSeparators) { this.separator = String.valueOf(separator); this.allowsMultipleRoots = allowsMultipleRoots; this.otherSeparators = String.valueOf(otherSeparators); this.joiner = Joiner.on(separator); this.splitter = createSplitter(separator, otherSeparators); } private static final char[] regexReservedChars = "^$.?+*\\[]{}()".toCharArray(); static { Arrays.sort(regexReservedChars); } private static boolean isRegexReserved(char c) { return Arrays.binarySearch(regexReservedChars, c) >= 0; } private static Splitter createSplitter(char separator, char... otherSeparators) { if (otherSeparators.length == 0) { return Splitter.on(separator).omitEmptyStrings(); } // TODO(cgdecker): When CharMatcher is out of @Beta, us Splitter.on(CharMatcher) StringBuilder patternBuilder = new StringBuilder(); patternBuilder.append("["); appendToRegex(separator, patternBuilder); for (char other : otherSeparators) { appendToRegex(other, patternBuilder); } patternBuilder.append("]"); return Splitter.onPattern(patternBuilder.toString()).omitEmptyStrings(); } private static void appendToRegex(char separator, StringBuilder patternBuilder) { if (isRegexReserved(separator)) { patternBuilder.append("\\"); } patternBuilder.append(separator); } /** Returns whether or not this type of path allows multiple root directories. */ public final boolean allowsMultipleRoots() { return allowsMultipleRoots; } /** * Returns the canonical separator for this path type. The returned string always has a length of * one. */ public final String getSeparator() { return separator; } /** * Returns the other separators that are recognized when parsing a path. If no other separators * are recognized, the empty string is returned. */ public final String getOtherSeparators() { return otherSeparators; } /** Returns the path joiner for this path type. */ public final Joiner joiner() { return joiner; } /** Returns the path splitter for this path type. */ public final Splitter splitter() { return splitter; } /** Returns an empty path. */ protected final ParseResult emptyPath() { return new ParseResult(null, ImmutableList.of("")); } /** * Parses the given strings as a path. * * @throws InvalidPathException if the path isn't valid for this path type */ public abstract ParseResult parsePath(String path); @Override public String toString() { return getClass().getSimpleName(); } /** Returns the string form of the given path. */ public abstract String toString(@Nullable String root, Iterable<String> names); /** * Returns the string form of the given path for use in the path part of a URI. The root element * is not nullable as the path must be absolute. The elements of the returned path <i>do not</i> * need to be escaped. The {@code directory} boolean indicates whether the file the URI is for is * known to be a directory. */ protected abstract String toUriPath(String root, Iterable<String> names, boolean directory); /** * Parses a path from the given URI path. * * @throws InvalidPathException if the given path isn't valid for this path type */ protected abstract ParseResult parseUriPath(String uriPath); /** * Creates a URI for the path with the given root and names in the file system with the given URI. */ public final URI toUri( URI fileSystemUri, String root, Iterable<String> names, boolean directory) {<FILL_FUNCTION_BODY>} /** Parses a path from the given URI. */ public final ParseResult fromUri(URI uri) { return parseUriPath(uri.getPath()); } /** Simple result of parsing a path. */ public static final class ParseResult { private final @Nullable String root; private final Iterable<String> names; public ParseResult(@Nullable String root, Iterable<String> names) { this.root = root; this.names = checkNotNull(names); } /** Returns whether or not this result is an absolute path. */ public boolean isAbsolute() { return root != null; } /** Returns whether or not this result represents a root path. */ public boolean isRoot() { return root != null && Iterables.isEmpty(names); } /** Returns the parsed root element, or null if there was no root. */ public @Nullable String root() { return root; } /** Returns the parsed name elements. */ public Iterable<String> names() { return names; } } }
String path = toUriPath(root, names, directory); try { // it should not suck this much to create a new URI that's the same except with a path set =( // need to do it this way for automatic path escaping return new URI( fileSystemUri.getScheme(), fileSystemUri.getUserInfo(), fileSystemUri.getHost(), fileSystemUri.getPort(), path, null, null); } catch (URISyntaxException e) { throw new AssertionError(e); }
1,814
144
1,958
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/PathURLConnection.java
PathURLConnection
toUri
class PathURLConnection extends URLConnection { /* * This implementation should be able to work for any proper file system implementation... it * might be useful to release it and make it usable by other file systems. */ private static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss \'GMT\'"; private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; private InputStream stream; private ImmutableListMultimap<String, String> headers = ImmutableListMultimap.of(); PathURLConnection(URL url) { super(checkNotNull(url)); } @Override public void connect() throws IOException { if (stream != null) { return; } Path path = Paths.get(toUri(url)); long length; if (Files.isDirectory(path)) { // Match File URL behavior for directories by having the stream contain the filenames in // the directory separated by newlines. StringBuilder builder = new StringBuilder(); try (DirectoryStream<Path> files = Files.newDirectoryStream(path)) { for (Path file : files) { builder.append(file.getFileName()).append('\n'); } } byte[] bytes = builder.toString().getBytes(UTF_8); stream = new ByteArrayInputStream(bytes); length = bytes.length; } else { stream = Files.newInputStream(path); length = Files.size(path); } FileTime lastModified = Files.getLastModifiedTime(path); String contentType = MoreObjects.firstNonNull(Files.probeContentType(path), DEFAULT_CONTENT_TYPE); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); builder.put("content-length", "" + length); builder.put("content-type", contentType); if (lastModified != null) { DateFormat format = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); builder.put("last-modified", format.format(new Date(lastModified.toMillis()))); } headers = builder.build(); } private static URI toUri(URL url) throws IOException {<FILL_FUNCTION_BODY>} @Override public InputStream getInputStream() throws IOException { connect(); return stream; } @SuppressWarnings("unchecked") // safe by specification of ListMultimap.asMap() @Override public Map<String, List<String>> getHeaderFields() { try { connect(); } catch (IOException e) { return ImmutableMap.of(); } return (ImmutableMap<String, List<String>>) (ImmutableMap<String, ?>) headers.asMap(); } @Override public @Nullable String getHeaderField(String name) { try { connect(); } catch (IOException e) { return null; } // no header should have more than one value return Iterables.getFirst(headers.get(Ascii.toLowerCase(name)), null); } }
try { return url.toURI(); } catch (URISyntaxException e) { throw new IOException("URL " + url + " cannot be converted to a URI", e); }
832
51
883
<methods>public void addRequestProperty(java.lang.String, java.lang.String) ,public abstract void connect() throws java.io.IOException,public boolean getAllowUserInteraction() ,public int getConnectTimeout() ,public java.lang.Object getContent() throws java.io.IOException,public java.lang.Object getContent(Class<?>[]) throws java.io.IOException,public java.lang.String getContentEncoding() ,public int getContentLength() ,public long getContentLengthLong() ,public java.lang.String getContentType() ,public long getDate() ,public static boolean getDefaultAllowUserInteraction() ,public static java.lang.String getDefaultRequestProperty(java.lang.String) ,public boolean getDefaultUseCaches() ,public static boolean getDefaultUseCaches(java.lang.String) ,public boolean getDoInput() ,public boolean getDoOutput() ,public long getExpiration() ,public static java.net.FileNameMap getFileNameMap() ,public java.lang.String getHeaderField(java.lang.String) ,public java.lang.String getHeaderField(int) ,public long getHeaderFieldDate(java.lang.String, long) ,public int getHeaderFieldInt(java.lang.String, int) ,public java.lang.String getHeaderFieldKey(int) ,public long getHeaderFieldLong(java.lang.String, long) ,public Map<java.lang.String,List<java.lang.String>> getHeaderFields() ,public long getIfModifiedSince() ,public java.io.InputStream getInputStream() throws java.io.IOException,public long getLastModified() ,public java.io.OutputStream getOutputStream() throws java.io.IOException,public java.security.Permission getPermission() throws java.io.IOException,public int getReadTimeout() ,public Map<java.lang.String,List<java.lang.String>> getRequestProperties() ,public java.lang.String getRequestProperty(java.lang.String) ,public java.net.URL getURL() ,public boolean getUseCaches() ,public static java.lang.String guessContentTypeFromName(java.lang.String) ,public static java.lang.String guessContentTypeFromStream(java.io.InputStream) throws java.io.IOException,public void setAllowUserInteraction(boolean) ,public void setConnectTimeout(int) ,public static synchronized void setContentHandlerFactory(java.net.ContentHandlerFactory) ,public static void setDefaultAllowUserInteraction(boolean) ,public static void setDefaultRequestProperty(java.lang.String, java.lang.String) ,public void setDefaultUseCaches(boolean) ,public static void setDefaultUseCaches(java.lang.String, boolean) ,public void setDoInput(boolean) ,public void setDoOutput(boolean) ,public static void setFileNameMap(java.net.FileNameMap) ,public void setIfModifiedSince(long) ,public void setReadTimeout(int) ,public void setRequestProperty(java.lang.String, java.lang.String) ,public void setUseCaches(boolean) ,public java.lang.String toString() <variables>static final boolean $assertionsDisabled,protected boolean allowUserInteraction,private int connectTimeout,protected boolean connected,private static final java.lang.String contentClassPrefix,private static final java.lang.String contentPathProp,private static boolean defaultAllowUserInteraction,private static final ConcurrentHashMap<java.lang.String,java.lang.Boolean> defaultCaching,private static volatile boolean defaultUseCaches,protected boolean doInput,protected boolean doOutput,private static volatile java.net.ContentHandlerFactory factory,private static volatile java.net.FileNameMap fileNameMap,private static final Hashtable<java.lang.String,java.net.ContentHandler> handlers,protected long ifModifiedSince,private int readTimeout,private sun.net.www.MessageHeader requests,protected java.net.URL url,protected boolean useCaches
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/PollingWatchService.java
Snapshot
postChanges
class Snapshot { /** Maps directory entry names to last modified times. */ private final ImmutableMap<Name, FileTime> modifiedTimes; Snapshot(Map<Name, FileTime> modifiedTimes) { this.modifiedTimes = ImmutableMap.copyOf(modifiedTimes); } /** * Posts events to the given key based on the kinds of events it subscribes to and what events * have occurred between this state and the given new state. */ boolean postChanges(Snapshot newState, Key key) {<FILL_FUNCTION_BODY>} }
boolean changesPosted = false; if (key.subscribesTo(ENTRY_CREATE)) { Set<Name> created = Sets.difference(newState.modifiedTimes.keySet(), modifiedTimes.keySet()); for (Name name : created) { key.post(new Event<>(ENTRY_CREATE, 1, pathService.createFileName(name))); changesPosted = true; } } if (key.subscribesTo(ENTRY_DELETE)) { Set<Name> deleted = Sets.difference(modifiedTimes.keySet(), newState.modifiedTimes.keySet()); for (Name name : deleted) { key.post(new Event<>(ENTRY_DELETE, 1, pathService.createFileName(name))); changesPosted = true; } } if (key.subscribesTo(ENTRY_MODIFY)) { for (Map.Entry<Name, FileTime> entry : modifiedTimes.entrySet()) { Name name = entry.getKey(); FileTime modifiedTime = entry.getValue(); FileTime newModifiedTime = newState.modifiedTimes.get(name); if (newModifiedTime != null && !modifiedTime.equals(newModifiedTime)) { key.post(new Event<>(ENTRY_MODIFY, 1, pathService.createFileName(name))); changesPosted = true; } } } return changesPosted;
149
375
524
<methods>public void cancelled(com.google.common.jimfs.AbstractWatchService.Key) ,public void close() ,public boolean isOpen() ,public java.nio.file.WatchKey poll() ,public java.nio.file.WatchKey poll(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public com.google.common.jimfs.AbstractWatchService.Key register(java.nio.file.Watchable, Iterable<? extends Kind<?>>) throws java.io.IOException,public java.nio.file.WatchKey take() throws java.lang.InterruptedException<variables>private final java.util.concurrent.atomic.AtomicBoolean open,private final java.nio.file.WatchKey poison,private final BlockingQueue<java.nio.file.WatchKey> queue
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/PosixAttributeProvider.java
PosixAttributeProvider
set
class PosixAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("group", "permissions"); private static final ImmutableSet<String> INHERITED_VIEWS = ImmutableSet.of("basic", "owner"); private static final GroupPrincipal DEFAULT_GROUP = createGroupPrincipal("group"); private static final ImmutableSet<PosixFilePermission> DEFAULT_PERMISSIONS = Sets.immutableEnumSet(PosixFilePermissions.fromString("rw-r--r--")); @Override public String name() { return "posix"; } @Override public ImmutableSet<String> inherits() { return INHERITED_VIEWS; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @SuppressWarnings("unchecked") @Override public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) { Object userProvidedGroup = userProvidedDefaults.get("posix:group"); UserPrincipal group = DEFAULT_GROUP; if (userProvidedGroup != null) { if (userProvidedGroup instanceof String) { group = createGroupPrincipal((String) userProvidedGroup); } else { throw new IllegalArgumentException( "invalid type " + userProvidedGroup.getClass().getName() + " for attribute 'posix:group': should be one of " + String.class + " or " + GroupPrincipal.class); } } Object userProvidedPermissions = userProvidedDefaults.get("posix:permissions"); Set<PosixFilePermission> permissions = DEFAULT_PERMISSIONS; if (userProvidedPermissions != null) { if (userProvidedPermissions instanceof String) { permissions = Sets.immutableEnumSet( PosixFilePermissions.fromString((String) userProvidedPermissions)); } else if (userProvidedPermissions instanceof Set) { permissions = toPermissions((Set<?>) userProvidedPermissions); } else { throw new IllegalArgumentException( "invalid type " + userProvidedPermissions.getClass().getName() + " for attribute 'posix:permissions': should be one of " + String.class + " or " + Set.class); } } return ImmutableMap.of( "posix:group", group, "posix:permissions", permissions); } @Override public @Nullable Object get(File file, String attribute) { switch (attribute) { case "group": return file.getAttribute("posix", "group"); case "permissions": return file.getAttribute("posix", "permissions"); default: return null; } } @Override public void set(File file, String view, String attribute, Object value, boolean create) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") // only cast after checking each element's type private static ImmutableSet<PosixFilePermission> toPermissions(Set<?> set) { ImmutableSet<?> copy = ImmutableSet.copyOf(set); for (Object obj : copy) { if (!(obj instanceof PosixFilePermission)) { throw new IllegalArgumentException( "invalid element for attribute 'posix:permissions': " + "should be Set<PosixFilePermission>, found element of type " + obj.getClass()); } } return Sets.immutableEnumSet((ImmutableSet<PosixFilePermission>) copy); } @Override public Class<PosixFileAttributeView> viewType() { return PosixFileAttributeView.class; } @Override public PosixFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View( lookup, (BasicFileAttributeView) inheritedViews.get("basic"), (FileOwnerAttributeView) inheritedViews.get("owner")); } @Override public Class<PosixFileAttributes> attributesType() { return PosixFileAttributes.class; } @Override public PosixFileAttributes readAttributes(File file) { return new Attributes(file); } /** Implementation of {@link PosixFileAttributeView}. */ private static class View extends AbstractAttributeView implements PosixFileAttributeView { private final BasicFileAttributeView basicView; private final FileOwnerAttributeView ownerView; protected View( FileLookup lookup, BasicFileAttributeView basicView, FileOwnerAttributeView ownerView) { super(lookup); this.basicView = checkNotNull(basicView); this.ownerView = checkNotNull(ownerView); } @Override public String name() { return "posix"; } @Override public PosixFileAttributes readAttributes() throws IOException { return new Attributes(lookupFile()); } @Override public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException { basicView.setTimes(lastModifiedTime, lastAccessTime, createTime); } @Override public void setPermissions(Set<PosixFilePermission> perms) throws IOException { lookupFile().setAttribute("posix", "permissions", ImmutableSet.copyOf(perms)); } @Override public void setGroup(GroupPrincipal group) throws IOException { lookupFile().setAttribute("posix", "group", checkNotNull(group)); } @Override public UserPrincipal getOwner() throws IOException { return ownerView.getOwner(); } @Override public void setOwner(UserPrincipal owner) throws IOException { ownerView.setOwner(owner); } } /** Implementation of {@link PosixFileAttributes}. */ static class Attributes extends BasicAttributeProvider.Attributes implements PosixFileAttributes { private final UserPrincipal owner; private final GroupPrincipal group; private final ImmutableSet<PosixFilePermission> permissions; @SuppressWarnings("unchecked") protected Attributes(File file) { super(file); this.owner = (UserPrincipal) file.getAttribute("owner", "owner"); this.group = (GroupPrincipal) file.getAttribute("posix", "group"); this.permissions = (ImmutableSet<PosixFilePermission>) file.getAttribute("posix", "permissions"); } @Override public UserPrincipal owner() { return owner; } @Override public GroupPrincipal group() { return group; } @Override public ImmutableSet<PosixFilePermission> permissions() { return permissions; } } }
switch (attribute) { case "group": checkNotCreate(view, attribute, create); GroupPrincipal group = checkType(view, attribute, value, GroupPrincipal.class); if (!(group instanceof UserLookupService.JimfsGroupPrincipal)) { group = createGroupPrincipal(group.getName()); } file.setAttribute("posix", "group", group); break; case "permissions": file.setAttribute( "posix", "permissions", toPermissions(checkType(view, attribute, value, Set.class))); break; default: }
1,779
158
1,937
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/StandardAttributeProviders.java
StandardAttributeProviders
get
class StandardAttributeProviders { private StandardAttributeProviders() {} private static final ImmutableMap<String, AttributeProvider> PROVIDERS = new ImmutableMap.Builder<String, AttributeProvider>() .put("basic", new BasicAttributeProvider()) .put("owner", new OwnerAttributeProvider()) .put("posix", new PosixAttributeProvider()) .put("dos", new DosAttributeProvider()) .put("acl", new AclAttributeProvider()) .put("user", new UserDefinedAttributeProvider()) .build(); /** * Returns the attribute provider for the given view, or {@code null} if the given view is not one * of the attribute views this supports. */ public static @Nullable AttributeProvider get(String view) {<FILL_FUNCTION_BODY>} }
AttributeProvider provider = PROVIDERS.get(view); if (provider == null && view.equals("unix")) { // create a new UnixAttributeProvider per file system, as it does some caching that should be // cleaned up when the file system is garbage collected return new UnixAttributeProvider(); } return provider;
208
88
296
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/UnixAttributeProvider.java
UnixAttributeProvider
toMode
class UnixAttributeProvider extends AttributeProvider { private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("uid", "ino", "dev", "nlink", "rdev", "ctime", "mode", "gid"); private static final ImmutableSet<String> INHERITED_VIEWS = ImmutableSet.of("basic", "owner", "posix"); private final AtomicInteger uidGenerator = new AtomicInteger(); private final ConcurrentMap<Object, Integer> idCache = new ConcurrentHashMap<>(); @Override public String name() { return "unix"; } @Override public ImmutableSet<String> inherits() { return INHERITED_VIEWS; } @Override public ImmutableSet<String> fixedAttributes() { return ATTRIBUTES; } @Override public Class<UnixFileAttributeView> viewType() { return UnixFileAttributeView.class; } @Override public UnixFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { // This method should not be called... and it cannot be called through the public APIs in // java.nio.file since there is no public UnixFileAttributeView type. throw new UnsupportedOperationException(); } // TODO(cgdecker): Since we can now guarantee that the owner/group for an file are our own // implementation of UserPrincipal/GroupPrincipal, it would be nice to have them store a unique // ID themselves and just get that rather than doing caching here. Then this could be a singleton // like the rest of the AttributeProviders. However, that would require a way for the owner/posix // providers to create their default principals using the lookup service for the specific file // system. /** Returns an ID that is guaranteed to be the same for any invocation with equal objects. */ private Integer getUniqueId(Object object) { Integer id = idCache.get(object); if (id == null) { id = uidGenerator.incrementAndGet(); Integer existing = idCache.putIfAbsent(object, id); if (existing != null) { return existing; } } return id; } @SuppressWarnings("unchecked") @Override public @Nullable Object get(File file, String attribute) { switch (attribute) { case "uid": UserPrincipal user = (UserPrincipal) file.getAttribute("owner", "owner"); return getUniqueId(user); case "gid": GroupPrincipal group = (GroupPrincipal) file.getAttribute("posix", "group"); return getUniqueId(group); case "mode": Set<PosixFilePermission> permissions = (Set<PosixFilePermission>) file.getAttribute("posix", "permissions"); return toMode(permissions); case "ctime": return file.getCreationTime(); case "rdev": return 0L; case "dev": return 1L; case "ino": return file.id(); case "nlink": return file.links(); default: return null; } } @Override public void set(File file, String view, String attribute, Object value, boolean create) { throw unsettable(view, attribute, create); } @SuppressWarnings("OctalInteger") private static int toMode(Set<PosixFilePermission> permissions) {<FILL_FUNCTION_BODY>} }
int result = 0; for (PosixFilePermission permission : permissions) { checkNotNull(permission); switch (permission) { case OWNER_READ: result |= 0400; // note: octal numbers break; case OWNER_WRITE: result |= 0200; break; case OWNER_EXECUTE: result |= 0100; break; case GROUP_READ: result |= 0040; break; case GROUP_WRITE: result |= 0020; break; case GROUP_EXECUTE: result |= 0010; break; case OTHERS_READ: result |= 0004; break; case OTHERS_WRITE: result |= 0002; break; case OTHERS_EXECUTE: result |= 0001; break; default: throw new AssertionError(); // no other possible values } } return result;
931
281
1,212
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/UnixPathType.java
UnixPathType
checkValid
class UnixPathType extends PathType { /** Unix path type. */ static final PathType INSTANCE = new UnixPathType(); private UnixPathType() { super(false, '/'); } @Override public ParseResult parsePath(String path) { if (path.isEmpty()) { return emptyPath(); } checkValid(path); String root = path.startsWith("/") ? "/" : null; return new ParseResult(root, splitter().split(path)); } private static void checkValid(String path) {<FILL_FUNCTION_BODY>} @Override public String toString(@Nullable String root, Iterable<String> names) { StringBuilder builder = new StringBuilder(); if (root != null) { builder.append(root); } joiner().appendTo(builder, names); return builder.toString(); } @Override public String toUriPath(String root, Iterable<String> names, boolean directory) { StringBuilder builder = new StringBuilder(); for (String name : names) { builder.append('/').append(name); } if (directory || builder.length() == 0) { builder.append('/'); } return builder.toString(); } @Override public ParseResult parseUriPath(String uriPath) { checkArgument(uriPath.startsWith("/"), "uriPath (%s) must start with /", uriPath); return parsePath(uriPath); } }
int nulIndex = path.indexOf('\0'); if (nulIndex != -1) { throw new InvalidPathException(path, "nul character not allowed", nulIndex); }
400
54
454
<methods>public final boolean allowsMultipleRoots() ,public final com.google.common.jimfs.PathType.ParseResult fromUri(java.net.URI) ,public final java.lang.String getOtherSeparators() ,public final java.lang.String getSeparator() ,public final Joiner joiner() ,public abstract com.google.common.jimfs.PathType.ParseResult parsePath(java.lang.String) ,public final Splitter splitter() ,public java.lang.String toString() ,public abstract java.lang.String toString(java.lang.String, Iterable<java.lang.String>) ,public final java.net.URI toUri(java.net.URI, java.lang.String, Iterable<java.lang.String>, boolean) ,public static com.google.common.jimfs.PathType unix() ,public static com.google.common.jimfs.PathType windows() <variables>private final non-sealed boolean allowsMultipleRoots,private final non-sealed Joiner joiner,private final non-sealed java.lang.String otherSeparators,private static final char[] regexReservedChars,private final non-sealed java.lang.String separator,private final non-sealed Splitter splitter
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/UserDefinedAttributeProvider.java
View
getStoredBytes
class View extends AbstractAttributeView implements UserDefinedFileAttributeView { public View(FileLookup lookup) { super(lookup); } @Override public String name() { return "user"; } @Override public List<String> list() throws IOException { return userDefinedAttributes(lookupFile()).asList(); } private byte[] getStoredBytes(String name) throws IOException {<FILL_FUNCTION_BODY>} @Override public int size(String name) throws IOException { return getStoredBytes(name).length; } @Override public int read(String name, ByteBuffer dst) throws IOException { byte[] bytes = getStoredBytes(name); dst.put(bytes); return bytes.length; } @Override public int write(String name, ByteBuffer src) throws IOException { byte[] bytes = new byte[src.remaining()]; src.get(bytes); lookupFile().setAttribute(name(), name, bytes); return bytes.length; } @Override public void delete(String name) throws IOException { lookupFile().deleteAttribute(name(), name); } }
byte[] bytes = (byte[]) lookupFile().getAttribute(name(), name); if (bytes == null) { throw new IllegalArgumentException("attribute '" + name() + ":" + name + "' is not set"); } return bytes;
311
63
374
<methods>public non-sealed void <init>() ,public ImmutableSet<java.lang.String> attributes(com.google.common.jimfs.File) ,public Class<? extends java.nio.file.attribute.BasicFileAttributes> attributesType() ,public ImmutableMap<java.lang.String,?> defaultValues(Map<java.lang.String,?>) ,public abstract ImmutableSet<java.lang.String> fixedAttributes() ,public abstract java.lang.Object get(com.google.common.jimfs.File, java.lang.String) ,public ImmutableSet<java.lang.String> inherits() ,public abstract java.lang.String name() ,public java.nio.file.attribute.BasicFileAttributes readAttributes(com.google.common.jimfs.File) ,public abstract void set(com.google.common.jimfs.File, java.lang.String, java.lang.String, java.lang.Object, boolean) ,public boolean supports(java.lang.String) ,public abstract java.nio.file.attribute.FileAttributeView view(com.google.common.jimfs.FileLookup, ImmutableMap<java.lang.String,java.nio.file.attribute.FileAttributeView>) ,public abstract Class<? extends java.nio.file.attribute.FileAttributeView> viewType() <variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/UserLookupService.java
UserLookupService
lookupPrincipalByGroupName
class UserLookupService extends UserPrincipalLookupService { private final boolean supportsGroups; public UserLookupService(boolean supportsGroups) { this.supportsGroups = supportsGroups; } @Override public UserPrincipal lookupPrincipalByName(String name) { return createUserPrincipal(name); } @Override public GroupPrincipal lookupPrincipalByGroupName(String group) throws IOException {<FILL_FUNCTION_BODY>} /** Creates a {@link UserPrincipal} for the given user name. */ static UserPrincipal createUserPrincipal(String name) { return new JimfsUserPrincipal(name); } /** Creates a {@link GroupPrincipal} for the given group name. */ static GroupPrincipal createGroupPrincipal(String name) { return new JimfsGroupPrincipal(name); } /** Base class for {@link UserPrincipal} and {@link GroupPrincipal} implementations. */ private abstract static class NamedPrincipal implements UserPrincipal { protected final String name; private NamedPrincipal(String name) { this.name = checkNotNull(name); } @Override public final String getName() { return name; } @Override public final int hashCode() { return name.hashCode(); } @Override public final String toString() { return name; } } /** {@link UserPrincipal} implementation. */ static final class JimfsUserPrincipal extends NamedPrincipal { private JimfsUserPrincipal(String name) { super(name); } @Override public boolean equals(Object obj) { return obj instanceof JimfsUserPrincipal && getName().equals(((JimfsUserPrincipal) obj).getName()); } } /** {@link GroupPrincipal} implementation. */ static final class JimfsGroupPrincipal extends NamedPrincipal implements GroupPrincipal { private JimfsGroupPrincipal(String name) { super(name); } @Override public boolean equals(Object obj) { return obj instanceof JimfsGroupPrincipal && ((JimfsGroupPrincipal) obj).name.equals(name); } } }
if (!supportsGroups) { throw new UserPrincipalNotFoundException(group); // required by spec } return createGroupPrincipal(group);
575
41
616
<methods>public abstract java.nio.file.attribute.GroupPrincipal lookupPrincipalByGroupName(java.lang.String) throws java.io.IOException,public abstract java.nio.file.attribute.UserPrincipal lookupPrincipalByName(java.lang.String) throws java.io.IOException<variables>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/Util.java
Util
clear
class Util { private Util() {} /** Returns the next power of 2 >= n. */ public static int nextPowerOf2(int n) { if (n == 0) { return 1; } int b = Integer.highestOneBit(n); return b == n ? n : b << 1; } /** * Checks that the given number is not negative, throwing IAE if it is. The given description * describes the number in the exception message. */ static void checkNotNegative(long n, String description) { checkArgument(n >= 0, "%s must not be negative: %s", description, n); } /** Checks that no element in the given iterable is null, throwing NPE if any is. */ static void checkNoneNull(Iterable<?> objects) { if (!(objects instanceof ImmutableCollection)) { for (Object o : objects) { checkNotNull(o); } } } private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; /* * This method was rewritten in Java from an intermediate step of the Murmur hash function in * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the * following header: * * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author * hereby disclaims copyright to this source code. */ static int smearHash(int hashCode) { return C2 * Integer.rotateLeft(hashCode * C1, 15); } private static final int ARRAY_LEN = 8192; private static final byte[] ZERO_ARRAY = new byte[ARRAY_LEN]; private static final byte[][] NULL_ARRAY = new byte[ARRAY_LEN][]; /** Zeroes all bytes between off (inclusive) and off + len (exclusive) in the given array. */ static void zero(byte[] bytes, int off, int len) { // this is significantly faster than looping or Arrays.fill (which loops), particularly when // the length of the slice to be zeroed is <= to ARRAY_LEN (in that case, it's faster by a // factor of 2) int remaining = len; while (remaining > ARRAY_LEN) { System.arraycopy(ZERO_ARRAY, 0, bytes, off, ARRAY_LEN); off += ARRAY_LEN; remaining -= ARRAY_LEN; } System.arraycopy(ZERO_ARRAY, 0, bytes, off, remaining); } /** * Clears (sets to null) all blocks between off (inclusive) and off + len (exclusive) in the given * array. */ static void clear(byte[][] blocks, int off, int len) {<FILL_FUNCTION_BODY>} }
// this is significantly faster than looping or Arrays.fill (which loops), particularly when // the length of the slice to be cleared is <= to ARRAY_LEN (in that case, it's faster by a // factor of 2) int remaining = len; while (remaining > ARRAY_LEN) { System.arraycopy(NULL_ARRAY, 0, blocks, off, ARRAY_LEN); off += ARRAY_LEN; remaining -= ARRAY_LEN; } System.arraycopy(NULL_ARRAY, 0, blocks, off, remaining);
781
154
935
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/WatchServiceConfiguration.java
PollingConfig
toString
class PollingConfig extends WatchServiceConfiguration { private final long interval; private final TimeUnit timeUnit; private PollingConfig(long interval, TimeUnit timeUnit) { checkArgument(interval > 0, "interval (%s) must be positive", interval); this.interval = interval; this.timeUnit = checkNotNull(timeUnit); } @Override AbstractWatchService newWatchService(FileSystemView view, PathService pathService) { return new PollingWatchService(view, pathService, view.state(), interval, timeUnit); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "WatchServiceConfiguration.polling(" + interval + ", " + timeUnit + ")";
168
25
193
<no_super_class>
google_jimfs
jimfs/jimfs/src/main/java/com/google/common/jimfs/WindowsPathType.java
WindowsPathType
parsePath
class WindowsPathType extends PathType { /** Windows path type. */ static final WindowsPathType INSTANCE = new WindowsPathType(); /** * Matches the C:foo\bar path format, which has a root (C:) and names (foo\bar) and matches a path * relative to the working directory on that drive. Currently can't support that format as it * requires behavior that differs completely from Unix. */ // TODO(cgdecker): Can probably support this at some point // It would require: // - A method like PathType.isAbsolute(Path) or something to that effect; this would allow // WindowsPathType to distinguish between an absolute root path (C:\) and a relative root // path (C:) // - Special handling for relative paths that have a root. This handling would determine the // root directory and then determine the working directory from there. The file system would // still have one working directory; for the root that working directory is under, it is the // working directory. For every other root, the root itself is the working directory. private static final Pattern WORKING_DIR_WITH_DRIVE = Pattern.compile("^[a-zA-Z]:([^\\\\].*)?$"); /** Pattern for matching trailing spaces in file names. */ private static final Pattern TRAILING_SPACES = Pattern.compile("[ ]+(\\\\|$)"); private WindowsPathType() { super(true, '\\', '/'); } @Override public ParseResult parsePath(String path) {<FILL_FUNCTION_BODY>} /** Pattern for matching UNC \\host\share root syntax. */ private static final Pattern UNC_ROOT = Pattern.compile("^(\\\\\\\\)([^\\\\]+)?(\\\\[^\\\\]+)?"); /** * Parse the root of a UNC-style path, throwing an exception if the path does not start with a * valid UNC root. */ private String parseUncRoot(String path, String original) { Matcher uncMatcher = UNC_ROOT.matcher(path); if (uncMatcher.find()) { String host = uncMatcher.group(2); if (host == null) { throw new InvalidPathException(original, "UNC path is missing hostname"); } String share = uncMatcher.group(3); if (share == null) { throw new InvalidPathException(original, "UNC path is missing sharename"); } return path.substring(uncMatcher.start(), uncMatcher.end()); } else { // probably shouldn't ever reach this throw new InvalidPathException(original, "Invalid UNC path"); } } /** Pattern for matching normal C:\ drive letter root syntax. */ private static final Pattern DRIVE_LETTER_ROOT = Pattern.compile("^[a-zA-Z]:\\\\"); /** Parses a normal drive-letter root, e.g. "C:\". */ private @Nullable String parseDriveRoot(String path) { Matcher drivePathMatcher = DRIVE_LETTER_ROOT.matcher(path); if (drivePathMatcher.find()) { return path.substring(drivePathMatcher.start(), drivePathMatcher.end()); } return null; } /** Checks if c is one of the reserved characters that aren't allowed in Windows file names. */ private static boolean isReserved(char c) { switch (c) { case '<': case '>': case ':': case '"': case '|': case '?': case '*': return true; default: return c <= 31; } } @Override public String toString(@Nullable String root, Iterable<String> names) { StringBuilder builder = new StringBuilder(); if (root != null) { builder.append(root); } joiner().appendTo(builder, names); return builder.toString(); } @Override public String toUriPath(String root, Iterable<String> names, boolean directory) { if (root.startsWith("\\\\")) { root = root.replace('\\', '/'); } else { root = "/" + root.replace('\\', '/'); } StringBuilder builder = new StringBuilder(); builder.append(root); Iterator<String> iter = names.iterator(); if (iter.hasNext()) { builder.append(iter.next()); while (iter.hasNext()) { builder.append('/').append(iter.next()); } } if (directory && builder.charAt(builder.length() - 1) != '/') { builder.append('/'); } return builder.toString(); } @Override public ParseResult parseUriPath(String uriPath) { uriPath = uriPath.replace('/', '\\'); if (uriPath.charAt(0) == '\\' && uriPath.charAt(1) != '\\') { // non-UNC path, so the leading / was just there for the URI path format and isn't part // of what should be parsed uriPath = uriPath.substring(1); } return parsePath(uriPath); } }
String original = path; path = path.replace('/', '\\'); if (WORKING_DIR_WITH_DRIVE.matcher(path).matches()) { throw new InvalidPathException( original, "Jimfs does not currently support the Windows syntax for a relative path " + "on a specific drive (e.g. \"C:foo\\bar\")"); } String root; if (path.startsWith("\\\\")) { root = parseUncRoot(path, original); } else if (path.startsWith("\\")) { throw new InvalidPathException( original, "Jimfs does not currently support the Windows syntax for an absolute path " + "on the current drive (e.g. \"\\foo\\bar\")"); } else { root = parseDriveRoot(path); } // check for root.length() > 3 because only "C:\" type roots are allowed to have : int startIndex = root == null || root.length() > 3 ? 0 : root.length(); for (int i = startIndex; i < path.length(); i++) { char c = path.charAt(i); if (isReserved(c)) { throw new InvalidPathException(original, "Illegal char <" + c + ">", i); } } Matcher trailingSpaceMatcher = TRAILING_SPACES.matcher(path); if (trailingSpaceMatcher.find()) { throw new InvalidPathException(original, "Trailing char < >", trailingSpaceMatcher.start()); } if (root != null) { path = path.substring(root.length()); if (!root.endsWith("\\")) { root = root + "\\"; } } return new ParseResult(root, splitter().split(path));
1,374
477
1,851
<methods>public final boolean allowsMultipleRoots() ,public final com.google.common.jimfs.PathType.ParseResult fromUri(java.net.URI) ,public final java.lang.String getOtherSeparators() ,public final java.lang.String getSeparator() ,public final Joiner joiner() ,public abstract com.google.common.jimfs.PathType.ParseResult parsePath(java.lang.String) ,public final Splitter splitter() ,public java.lang.String toString() ,public abstract java.lang.String toString(java.lang.String, Iterable<java.lang.String>) ,public final java.net.URI toUri(java.net.URI, java.lang.String, Iterable<java.lang.String>, boolean) ,public static com.google.common.jimfs.PathType unix() ,public static com.google.common.jimfs.PathType windows() <variables>private final non-sealed boolean allowsMultipleRoots,private final non-sealed Joiner joiner,private final non-sealed java.lang.String otherSeparators,private static final char[] regexReservedChars,private final non-sealed java.lang.String separator,private final non-sealed Splitter splitter
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/BuildInfoMetrics.java
BuildInfoMetrics
register
class BuildInfoMetrics { /** * Method to register BuildInfoMetrics * * @return this BuildInfoMetrics */ public BuildInfoMetrics register() { return register(PrometheusRegistry.defaultRegistry); } /** * Method to register BuildInfoMetrics * * @param prometheusRegistry prometheusRegistry * @return this BuildInfoMetrics */ public BuildInfoMetrics register(PrometheusRegistry prometheusRegistry) {<FILL_FUNCTION_BODY>} }
Info info = Info.builder() .name("jmx_exporter_build_info") .help("JMX Exporter build information") .labelNames("name", "version") .register(prometheusRegistry); Package pkg = this.getClass().getPackage(); String name = pkg.getImplementationTitle(); String version = pkg.getImplementationVersion(); info.setLabelValues(name != null ? name : "unknown", version != null ? version : "unknown"); return this;
132
139
271
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/JmxCollector.java
Config
reloadConfig
class Config { Integer startDelaySeconds = 0; String jmxUrl = ""; String username = ""; String password = ""; boolean ssl = false; boolean lowercaseOutputName; boolean lowercaseOutputLabelNames; List<ObjectName> includeObjectNames = new ArrayList<>(); List<ObjectName> excludeObjectNames = new ArrayList<>(); ObjectNameAttributeFilter objectNameAttributeFilter; List<Rule> rules = new ArrayList<>(); long lastUpdate = 0L; MatchedRulesCache rulesCache; } private PrometheusRegistry prometheusRegistry; private Config config; private File configFile; private long createTimeNanoSecs = System.nanoTime(); private Counter configReloadSuccess; private Counter configReloadFailure; private Gauge jmxScrapeDurationSeconds; private Gauge jmxScrapeError; private Gauge jmxScrapeCachedBeans; private final JmxMBeanPropertyCache jmxMBeanPropertyCache = new JmxMBeanPropertyCache(); public JmxCollector(File in) throws IOException, MalformedObjectNameException { this(in, null); } public JmxCollector(File in, Mode mode) throws IOException, MalformedObjectNameException { configFile = in; this.mode = mode; config = loadConfig(new Yaml().load(new FileReader(in))); config.lastUpdate = configFile.lastModified(); exitOnConfigError(); } public JmxCollector(String yamlConfig) throws MalformedObjectNameException { config = loadConfig(new Yaml().load(yamlConfig)); mode = null; } public JmxCollector(InputStream inputStream) throws MalformedObjectNameException { config = loadConfig(new Yaml().load(inputStream)); mode = null; } public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); } public JmxCollector register(PrometheusRegistry prometheusRegistry) { this.prometheusRegistry = prometheusRegistry; configReloadSuccess = Counter.builder() .name("jmx_config_reload_success_total") .help("Number of times configuration have successfully been reloaded.") .register(prometheusRegistry); configReloadFailure = Counter.builder() .name("jmx_config_reload_failure_total") .help("Number of times configuration have failed to be reloaded.") .register(prometheusRegistry); jmxScrapeDurationSeconds = Gauge.builder() .name("jmx_scrape_duration_seconds") .help("Time this JMX scrape took, in seconds.") .unit(Unit.SECONDS) .register(prometheusRegistry); jmxScrapeError = Gauge.builder() .name("jmx_scrape_error") .help("Non-zero if this scrape failed.") .register(prometheusRegistry); jmxScrapeCachedBeans = Gauge.builder() .name("jmx_scrape_cached_beans") .help("Number of beans with their matching rule cached") .register(prometheusRegistry); prometheusRegistry.register(this); return this; } private void exitOnConfigError() { if (mode == Mode.AGENT && !config.jmxUrl.isEmpty()) { LOGGER.log( SEVERE, "Configuration error: When running jmx_exporter as a Java agent, you must not" + " configure 'jmxUrl' or 'hostPort' because you don't want to monitor a" + " remote JVM."); System.exit(-1); } if (mode == Mode.STANDALONE && config.jmxUrl.isEmpty()) { LOGGER.log( SEVERE, "Configuration error: When running jmx_exporter in standalone mode (using" + " jmx_prometheus_httpserver-*.jar) you must configure 'jmxUrl' or" + " 'hostPort'."); System.exit(-1); } } private void reloadConfig() {<FILL_FUNCTION_BODY>
try { FileReader fr = new FileReader(configFile); try { Map<String, Object> newYamlConfig = new Yaml().load(fr); config = loadConfig(newYamlConfig); config.lastUpdate = configFile.lastModified(); configReloadSuccess.inc(); } catch (Exception e) { LOGGER.log(SEVERE, "Configuration reload failed: %s: ", e); configReloadFailure.inc(); } finally { fr.close(); } } catch (IOException e) { LOGGER.log(SEVERE, "Configuration reload failed: %s", e); configReloadFailure.inc(); }
1,096
180
1,276
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/JmxMBeanPropertyCache.java
JmxMBeanPropertyCache
onlyKeepMBeans
class JmxMBeanPropertyCache { private static final Pattern PROPERTY_PATTERN = Pattern.compile( "([^,=:\\*\\?]+)" + // Name - non-empty, anything but comma, equals, colon, star, or // question mark "=" + // Equals "(" + // Either "\"" + // Quoted "(?:" + // A possibly empty sequence of "[^\\\\\"]*" + // Greedily match anything but backslash or quote "(?:\\\\.)?" + // Greedily see if we can match an escaped sequence ")*" + "\"" + "|" + // Or "[^,=:\"]*" + // Unquoted - can be empty, anything but comma, equals, colon, or // quote ")"); // Implement a version of ObjectName.getKeyPropertyList that returns the // properties in the ordered they were added (the ObjectName stores them // in the order they were added). private final Map<ObjectName, LinkedHashMap<String, String>> keyPropertiesPerBean; public JmxMBeanPropertyCache() { this.keyPropertiesPerBean = new ConcurrentHashMap<>(); } Map<ObjectName, LinkedHashMap<String, String>> getKeyPropertiesPerBean() { return keyPropertiesPerBean; } public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName); if (keyProperties == null) { keyProperties = new LinkedHashMap<>(); String properties = mbeanName.getKeyPropertyListString(); Matcher match = PROPERTY_PATTERN.matcher(properties); while (match.lookingAt()) { keyProperties.put(match.group(1), match.group(2)); properties = properties.substring(match.end()); if (properties.startsWith(",")) { properties = properties.substring(1); } match.reset(properties); } keyPropertiesPerBean.put(mbeanName, keyProperties); } return keyProperties; } public void onlyKeepMBeans(Set<ObjectName> latestBeans) {<FILL_FUNCTION_BODY>} }
for (ObjectName prevName : keyPropertiesPerBean.keySet()) { if (!latestBeans.contains(prevName)) { keyPropertiesPerBean.remove(prevName); } }
602
53
655
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/MatchedRulesCache.java
MatchedRulesCache
evictStaleEntries
class MatchedRulesCache { private final Map<JmxCollector.Rule, Map<String, MatchedRule>> cachedRules; public MatchedRulesCache(Collection<JmxCollector.Rule> rules) { this.cachedRules = new HashMap<>(rules.size()); for (JmxCollector.Rule rule : rules) { this.cachedRules.put(rule, new ConcurrentHashMap<>()); } } public void put( final JmxCollector.Rule rule, final String cacheKey, final MatchedRule matchedRule) { Map<String, MatchedRule> cachedRulesForRule = cachedRules.get(rule); cachedRulesForRule.put(cacheKey, matchedRule); } public MatchedRule get(final JmxCollector.Rule rule, final String cacheKey) { return cachedRules.get(rule).get(cacheKey); } // Remove stale rules (in the cache but not collected in the last run of the collector) public void evictStaleEntries(final StalenessTracker stalenessTracker) {<FILL_FUNCTION_BODY>} public static class StalenessTracker { private final Map<JmxCollector.Rule, Set<String>> lastCachedEntries = new HashMap<>(); public void add(final JmxCollector.Rule rule, final String cacheKey) { Set<String> lastCachedEntriesForRule = lastCachedEntries.computeIfAbsent(rule, k -> new HashSet<>()); lastCachedEntriesForRule.add(cacheKey); } public boolean contains(final JmxCollector.Rule rule, final String cacheKey) { Set<String> lastCachedEntriesForRule = lastCachedEntries.get(rule); return (lastCachedEntriesForRule != null) && lastCachedEntriesForRule.contains(cacheKey); } public long cachedCount() { long count = 0; for (Set<String> cacheKeys : lastCachedEntries.values()) { count += cacheKeys.size(); } return count; } } }
for (Map.Entry<JmxCollector.Rule, Map<String, MatchedRule>> entry : cachedRules.entrySet()) { JmxCollector.Rule rule = entry.getKey(); Map<String, MatchedRule> cachedRulesForRule = entry.getValue(); for (String cacheKey : cachedRulesForRule.keySet()) { if (!stalenessTracker.contains(rule, cacheKey)) { cachedRulesForRule.remove(cacheKey); } } }
548
131
679
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/ObjectNameAttributeFilter.java
ObjectNameAttributeFilter
add
class ObjectNameAttributeFilter { private static final Logger LOGGER = LoggerFactory.getLogger(ObjectNameAttributeFilter.class); /** Configuration constant to define a mapping of ObjectNames to attribute names */ public static final String EXCLUDE_OBJECT_NAME_ATTRIBUTES = "excludeObjectNameAttributes"; /** Configuration constant to enable auto ObjectName attributes filtering */ public static final String AUTO_EXCLUDE_OBJECT_NAME_ATTRIBUTES = "autoExcludeObjectNameAttributes"; private final Map<ObjectName, Set<String>> excludeObjectNameAttributesMap; private boolean autoExcludeObjectNameAttributes; /** Constructor */ private ObjectNameAttributeFilter() { excludeObjectNameAttributesMap = new ConcurrentHashMap<>(); } /** * Method to initialize the ObjectNameAttributeFilter * * @param yamlConfig yamlConfig * @return an ObjectNameAttributeFilter * @throws MalformedObjectNameException MalformedObjectNameException */ private ObjectNameAttributeFilter initialize(Map<String, Object> yamlConfig) throws MalformedObjectNameException { if (yamlConfig.containsKey(EXCLUDE_OBJECT_NAME_ATTRIBUTES)) { Map<Object, Object> objectNameAttributeMap = (Map<Object, Object>) yamlConfig.get(EXCLUDE_OBJECT_NAME_ATTRIBUTES); for (Map.Entry<Object, Object> entry : objectNameAttributeMap.entrySet()) { ObjectName objectName = new ObjectName((String) entry.getKey()); List<String> attributeNames = (List<String>) entry.getValue(); Set<String> attributeNameSet = excludeObjectNameAttributesMap.computeIfAbsent( objectName, o -> Collections.synchronizedSet(new HashSet<>())); attributeNameSet.addAll(attributeNames); for (String attribueName : attributeNames) { attributeNameSet.add(attribueName); } excludeObjectNameAttributesMap.put(objectName, attributeNameSet); } } if (yamlConfig.containsKey(AUTO_EXCLUDE_OBJECT_NAME_ATTRIBUTES)) { autoExcludeObjectNameAttributes = (Boolean) yamlConfig.get(AUTO_EXCLUDE_OBJECT_NAME_ATTRIBUTES); } else { autoExcludeObjectNameAttributes = true; } LOGGER.log(Level.FINE, "dynamicExclusion [%b]", autoExcludeObjectNameAttributes); return this; } /** * Method to add an attribute name to the filter if dynamic exclusion is enabled * * @param objectName the ObjectName * @param attributeName the attribute name */ public void add(ObjectName objectName, String attributeName) {<FILL_FUNCTION_BODY>} /** * Method to check if an attribute should be excluded * * @param objectName the ObjectName * @param attributeName the attribute name * @return true if it should be excluded, false otherwise */ public boolean exclude(ObjectName objectName, String attributeName) { boolean result = false; if (excludeObjectNameAttributesMap.size() > 0) { Set<String> attributeNameSet = excludeObjectNameAttributesMap.get(objectName); if (attributeNameSet != null) { result = attributeNameSet.contains(attributeName); } } return result; } /** * Method to create an ObjectNameAttributeFilter * * @param yamlConfig yamlConfig * @return an ObjectNameAttributeFilter */ public static ObjectNameAttributeFilter create(Map<String, Object> yamlConfig) { try { return new ObjectNameAttributeFilter().initialize(yamlConfig); } catch (MalformedObjectNameException e) { throw new RuntimeException( "Invalid configuration format for excludeObjectNameAttributes", e); } } }
if (autoExcludeObjectNameAttributes) { Set<String> attribteNameSet = excludeObjectNameAttributesMap.computeIfAbsent( objectName, o -> Collections.synchronizedSet(new HashSet<>())); LOGGER.log( Level.FINE, "auto adding exclusion of object name [%s] attribute name [%s]", objectName.getCanonicalName(), attributeName); attribteNameSet.add(attributeName); }
1,006
129
1,135
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/collector/src/main/java/io/prometheus/jmx/logger/Logger.java
Logger
log
class Logger { private final java.util.logging.Logger LOGGER; private final boolean JMX_PROMETHEUS_EXPORTER_DEVELOPER_DEBUG = "true".equals(System.getenv("JMX_PROMETHEUS_EXPORTER_DEVELOPER_DEBUG")) || "true".equals(System.getProperty("jmx.prometheus.exporter.developer.debug")); /** * Constructor * * @param clazz clazz */ Logger(Class<?> clazz) { LOGGER = java.util.logging.Logger.getLogger(clazz.getName()); } /** * Method to return whether a log level is enabled * * @param level level * @return true if the log level is enabled, else false */ public boolean isLoggable(Level level) { return LOGGER.isLoggable(level); } /** * Method to log a message * * @param level level * @param message message * @param objects objects */ public void log(Level level, String message, Object... objects) {<FILL_FUNCTION_BODY>} }
if (LOGGER.isLoggable(level)) { LOGGER.log(level, String.format(message, objects)); } if (JMX_PROMETHEUS_EXPORTER_DEVELOPER_DEBUG) { System.out .format("[%s] %s %s", level, LOGGER.getName(), String.format(message, objects)) .println(); }
314
108
422
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/configuration/ConvertToInteger.java
ConvertToInteger
apply
class ConvertToInteger implements Function<Object, Integer> { private final Supplier<? extends RuntimeException> supplier; /** * Constructor * * @param supplier supplier */ public ConvertToInteger(Supplier<? extends RuntimeException> supplier) { Precondition.notNull(supplier); this.supplier = supplier; } /** * Method to apply a function * * @param value value * @return the return value */ @Override public Integer apply(Object value) {<FILL_FUNCTION_BODY>} }
if (value == null) { throw new IllegalArgumentException(); } try { return Integer.parseInt(value.toString()); } catch (Throwable t) { throw supplier.get(); }
152
59
211
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/configuration/ConvertToMapAccessor.java
ConvertToMapAccessor
apply
class ConvertToMapAccessor implements Function<Object, YamlMapAccessor> { private final Supplier<? extends RuntimeException> supplier; /** * Constructor * * @param supplier supplier */ public ConvertToMapAccessor(Supplier<? extends RuntimeException> supplier) { Precondition.notNull(supplier); this.supplier = supplier; } /** * Method to apply a function * * @param value value * @return the return value */ @Override public YamlMapAccessor apply(Object value) {<FILL_FUNCTION_BODY>} }
try { return new YamlMapAccessor((Map<Object, Object>) value); } catch (ClassCastException e) { throw supplier.get(); }
164
47
211
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/configuration/ConvertToString.java
ConvertToString
apply
class ConvertToString implements Function<Object, String> { private final Supplier<? extends RuntimeException> supplier; /** * Constructor * * @param supplier supplier */ public ConvertToString(Supplier<? extends RuntimeException> supplier) { Precondition.notNull(supplier); this.supplier = supplier; } /** * Method to apply a function * * @param value value * @return the return value */ @Override public String apply(Object value) {<FILL_FUNCTION_BODY>} }
if (value == null) { throw new IllegalArgumentException(); } try { return (String) value; } catch (Throwable t) { throw supplier.get(); }
150
55
205
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/configuration/ValidateIntegerInRange.java
ValidateIntegerInRange
apply
class ValidateIntegerInRange implements Function<Integer, Integer> { private final int minimum; private final int maximum; private final Supplier<? extends RuntimeException> supplier; /** * Constructor * * @param minimum minimum * @param maximum maximum * @param supplier supplier */ public ValidateIntegerInRange( int minimum, int maximum, Supplier<? extends RuntimeException> supplier) { Precondition.notNull(supplier); this.minimum = minimum; this.maximum = maximum; this.supplier = supplier; } /** * Method to apply a function * * @param value value * @return the return value */ @Override public Integer apply(Integer value) {<FILL_FUNCTION_BODY>} }
if (value < minimum || value > maximum) { throw supplier.get(); } return value;
209
32
241
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/authenticator/Credentials.java
Credentials
equals
class Credentials { private final String username; private final String password; /** * Constructor * * @param username username * @param password password */ public Credentials(String username, String password) { this.username = username; this.password = password; } /** * Method to get the size (username length + password length) of the credentials * * @return the size of the credentials */ public int size() { return username.length() + password.length(); } @Override public String toString() { return username + password; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(username, password); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Credentials Credentials = (Credentials) o; return Objects.equals(username, Credentials.username) && Objects.equals(password, Credentials.password);
223
82
305
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/authenticator/CredentialsCache.java
CredentialsCache
add
class CredentialsCache { private final int maximumCacheSizeBytes; private final LinkedHashMap<Credentials, Byte> linkedHashMap; private final LinkedList<Credentials> linkedList; private int currentCacheSizeBytes; /** * Constructor * * @param maximumCacheSizeBytes maximum cache size in bytes */ public CredentialsCache(int maximumCacheSizeBytes) { this.maximumCacheSizeBytes = maximumCacheSizeBytes; linkedHashMap = new LinkedHashMap<>(); linkedList = new LinkedList<>(); } /** * Method to add a Credentials to the cache * * <p>A credential that exceeds maximumCacheSizeBytes is not cached * * @param credentials credential */ public synchronized void add(Credentials credentials) {<FILL_FUNCTION_BODY>} /** * Method to return whether the cache contains the Credentials * * @param credentials credentials * @return true if the set contains the Credential, else false */ public synchronized boolean contains(Credentials credentials) { return linkedHashMap.containsKey(credentials); } /** * Method to remove a Credentials from the cache * * @param credentials credentials * @return true if the Credentials existed and was removed, else false */ public synchronized boolean remove(Credentials credentials) { if (linkedHashMap.remove(credentials) != null) { linkedList.remove(credentials); currentCacheSizeBytes -= credentials.toString().getBytes(StandardCharsets.UTF_8).length; return true; } else { return false; } } /** * Method to get the maximum cache size in bytes * * @return the maximum cache size in bytes */ public int getMaximumCacheSizeBytes() { return maximumCacheSizeBytes; } /** * Method to get the current cache size in bytes * * @return the current cache size in bytes */ public synchronized int getCurrentCacheSizeBytes() { return currentCacheSizeBytes; } }
int credentialSizeBytes = credentials.toString().getBytes(StandardCharsets.UTF_8).length; // Don't cache the entry since it's bigger than the maximum cache size // Don't invalidate other entries if (credentialSizeBytes > maximumCacheSizeBytes) { return; } // Purge old cache entries until we have space or the cache is empty while (((currentCacheSizeBytes + credentialSizeBytes) > maximumCacheSizeBytes) && (currentCacheSizeBytes > 0)) { Credentials c = linkedList.removeLast(); linkedHashMap.remove(c); currentCacheSizeBytes -= credentialSizeBytes; if (currentCacheSizeBytes < 0) { currentCacheSizeBytes = 0; } } linkedHashMap.put(credentials, (byte) 1); linkedList.addFirst(credentials); currentCacheSizeBytes += credentialSizeBytes;
546
235
781
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/authenticator/HexString.java
HexString
toHex
class HexString { private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); /** Constructor */ private HexString() { // DO NOTHING } /** * Method to convert a byte array to a lowercase hexadecimal String * * @param bytes bytes * @return the return value */ public static String toHex(byte[] bytes) {<FILL_FUNCTION_BODY>} }
char[] hexChars = new char[bytes.length * 2]; for (int i = 0, j = 0; i < bytes.length; i++) { hexChars[j++] = HEX_ARRAY[(0xF0 & bytes[i]) >>> 4]; hexChars[j++] = HEX_ARRAY[0x0F & bytes[i]]; } return new String(hexChars).toLowerCase();
134
117
251
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/authenticator/MessageDigestAuthenticator.java
MessageDigestAuthenticator
checkCredentials
class MessageDigestAuthenticator extends BasicAuthenticator { private static final int MAXIMUM_VALID_CACHE_SIZE_BYTES = 1000000; // 1 MB private static final int MAXIMUM_INVALID_CACHE_SIZE_BYTES = 10000000; // 10 MB private final String username; private final String passwordHash; private final String algorithm; private final String salt; private final CredentialsCache validCredentialsCache; private final CredentialsCache invalidCredentialsCache; /** * Constructor * * @param realm realm * @param username username * @param passwordHash passwordHash * @param algorithm algorithm * @param salt salt * @throws NoSuchAlgorithmException NoSuchAlgorithmException */ public MessageDigestAuthenticator( String realm, String username, String passwordHash, String algorithm, String salt) throws GeneralSecurityException { super(realm); Precondition.notNullOrEmpty(username); Precondition.notNullOrEmpty(passwordHash); Precondition.notNullOrEmpty(algorithm); Precondition.notNullOrEmpty(salt); MessageDigest.getInstance(algorithm); this.username = username; this.passwordHash = passwordHash.toLowerCase().replace(":", ""); this.algorithm = algorithm; this.salt = salt; this.validCredentialsCache = new CredentialsCache(MAXIMUM_VALID_CACHE_SIZE_BYTES); this.invalidCredentialsCache = new CredentialsCache(MAXIMUM_INVALID_CACHE_SIZE_BYTES); } /** * called for each incoming request to verify the given name and password in the context of this * Authenticator's realm. Any caching of credentials must be done by the implementation of this * method * * @param username the username from the request * @param password the password from the request * @return <code>true</code> if the credentials are valid, <code>false</code> otherwise. */ @Override public boolean checkCredentials(String username, String password) {<FILL_FUNCTION_BODY>} /** * Method to generate a hash based on the configured message digest algorithm * * @param algorithm algorithm * @param salt salt * @param password password * @return the hash */ private static String generatePasswordHash(String algorithm, String salt, String password) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hash = digest.digest((salt + ":" + password).getBytes(StandardCharsets.UTF_8)); BigInteger number = new BigInteger(1, hash); return number.toString(16).toLowerCase(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } }
if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return true; } else if (invalidCredentialsCache.contains(credentials)) { return false; } boolean isValid = this.username.equals(username) && this.passwordHash.equals( generatePasswordHash(algorithm, salt, password)); if (isValid) { validCredentialsCache.add(credentials); } else { invalidCredentialsCache.add(credentials); } return isValid;
741
173
914
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.nio.charset.Charset) ,public com.sun.net.httpserver.Authenticator.Result authenticate(com.sun.net.httpserver.HttpExchange) ,public abstract boolean checkCredentials(java.lang.String, java.lang.String) ,public java.lang.String getRealm() <variables>private final java.nio.charset.Charset charset,private final boolean isUTF8,protected final java.lang.String realm
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/authenticator/PBKDF2Authenticator.java
PBKDF2Authenticator
generatePasswordHash
class PBKDF2Authenticator extends BasicAuthenticator { private static final int MAXIMUM_VALID_CACHE_SIZE_BYTES = 1000000; // 1 MB private static final int MAXIMUM_INVALID_CACHE_SIZE_BYTES = 10000000; // 10 MB private final String username; private final String passwordHash; private final String algorithm; private final String salt; private final int iterations; private final int keyLength; private final CredentialsCache validCredentialsCache; private final CredentialsCache invalidCredentialsCache; /** * Constructor * * @param realm realm * @param username username * @param passwordHash passwordHash * @param algorithm algorithm * @param salt salt * @param iterations iterations * @param keyLength keyLength * @throws NoSuchAlgorithmException NoSuchAlgorithmException */ public PBKDF2Authenticator( String realm, String username, String passwordHash, String algorithm, String salt, int iterations, int keyLength) throws GeneralSecurityException { super(realm); Precondition.notNullOrEmpty(username); Precondition.notNullOrEmpty(passwordHash); Precondition.notNullOrEmpty(algorithm); Precondition.notNullOrEmpty(salt); Precondition.isGreaterThanOrEqualTo(iterations, 1); Precondition.isGreaterThanOrEqualTo(keyLength, 1); SecretKeyFactory.getInstance(algorithm); this.username = username; this.passwordHash = passwordHash.toLowerCase().replace(":", ""); this.algorithm = algorithm; this.salt = salt; this.iterations = iterations; this.keyLength = keyLength; this.validCredentialsCache = new CredentialsCache(MAXIMUM_VALID_CACHE_SIZE_BYTES); this.invalidCredentialsCache = new CredentialsCache(MAXIMUM_INVALID_CACHE_SIZE_BYTES); } /** * called for each incoming request to verify the given name and password in the context of this * Authenticator's realm. Any caching of credentials must be done by the implementation of this * method * * @param username the username from the request * @param password the password from the request * @return <code>true</code> if the credentials are valid, <code>false</code> otherwise. */ @Override public boolean checkCredentials(String username, String password) { if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return true; } else if (invalidCredentialsCache.contains(credentials)) { return false; } boolean isValid = this.username.equals(username) && this.passwordHash.equals( generatePasswordHash( algorithm, salt, iterations, keyLength, password)); if (isValid) { validCredentialsCache.add(credentials); } else { invalidCredentialsCache.add(credentials); } return isValid; } /** * Method to generate a hash based on the configured secret key algorithm * * @param algorithm algorithm * @param salt salt * @param iterations iterations * @param keyLength keyLength * @param password password * @return the hash */ private static String generatePasswordHash( String algorithm, String salt, int iterations, int keyLength, String password) {<FILL_FUNCTION_BODY>} }
try { PBEKeySpec pbeKeySpec = new PBEKeySpec( password.toCharArray(), salt.getBytes(StandardCharsets.UTF_8), iterations, keyLength * 8); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); byte[] secretKeyBytes = secretKeyFactory.generateSecret(pbeKeySpec).getEncoded(); return HexString.toHex(secretKeyBytes); } catch (GeneralSecurityException e) { throw new RuntimeException(e); }
955
139
1,094
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.nio.charset.Charset) ,public com.sun.net.httpserver.Authenticator.Result authenticate(com.sun.net.httpserver.HttpExchange) ,public abstract boolean checkCredentials(java.lang.String, java.lang.String) ,public java.lang.String getRealm() <variables>private final java.nio.charset.Charset charset,private final boolean isUTF8,protected final java.lang.String realm
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/http/ssl/SSLContextFactory.java
SSLContextFactory
createSSLContext
class SSLContextFactory { private static final String[] PROTOCOLS = {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1"}; /** Constructor */ private SSLContextFactory() { // DO NOTHING } /** * Method to create an SSLContext * * @param keyStoreFilename keyStoreFilename * @param keyStorePassword keyStorePassword * @param certificateAlias certificateAlias * @return the return value * @throws GeneralSecurityException GeneralSecurityException * @throws IOException IOException */ public static SSLContext createSSLContext( String keyStoreFilename, String keyStorePassword, String certificateAlias) throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>} /** * Method to create an SSLContext, looping through more secure to less secure TLS protocols * * @return the return value * @throws GeneralSecurityException GeneralSecurityException */ private static SSLContext createSSLContext() throws GeneralSecurityException { // Loop through potential protocols since there doesn't appear // to be a way to get the most secure supported protocol for (String protocol : PROTOCOLS) { try { return SSLContext.getInstance(protocol); } catch (Throwable t) { // DO NOTHING } } throw new GeneralSecurityException("No supported TLS protocols found"); } }
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = Files.newInputStream(Paths.get(keyStoreFilename))) { // Load the keystore keyStore.load(inputStream, keyStorePassword.toCharArray()); // Loop through the certificate aliases in the keystore // building a set of certificate aliases that don't match // the requested certificate alias Set<String> certificateAliasesToRemove = new HashSet<>(); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String keyStoreCertificateAlias = aliases.nextElement(); if (!keyStoreCertificateAlias.equals(certificateAlias)) { certificateAliasesToRemove.add(keyStoreCertificateAlias); } } // Remove the certificate aliases that don't // match the requested certificate alias from the keystore for (String certificateAliasToRemove : certificateAliasesToRemove) { keyStore.deleteEntry(certificateAliasToRemove); } // Validate the keystore contains the certificate alias that is requested if (!keyStore.containsAlias(certificateAlias)) { throw new GeneralSecurityException( String.format( "certificate alias [%s] not found in keystore [%s]", certificateAlias, keyStoreFilename)); } // Create and initialize an SSLContext KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = createSSLContext(); sslContext.init( keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }
368
520
888
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/util/Precondition.java
Precondition
notNull
class Precondition { private Precondition() { // DO NOTHING } /** * Method to check an Object is not null * * @param object object */ public static void notNull(Object object) { notNull(object, "object is null"); } /** * Method to check an Object is not null * * @param object object * @param message message */ public static void notNull(Object object, String message) {<FILL_FUNCTION_BODY>} /** * Method to check that a String is not null and not empty * * @param string string */ public static void notNullOrEmpty(String string) { notNullOrEmpty(string, String.format("string [%s] is null or empty", string)); } /** * Method to check that a String is not null and not empty * * @param string string * @param message message */ public static void notNullOrEmpty(String string, String message) { if (string == null || string.trim().isEmpty()) { throw new IllegalArgumentException(message); } } /** * Method to check that an integer is greater than or equal to a value * * @param value value * @param minimumValue minimumValue */ public static void isGreaterThanOrEqualTo(int value, int minimumValue) { isGreaterThanOrEqualTo( value, minimumValue, String.format("value [%s] is less than minimum value [%s]", value, minimumValue)); } /** * Method to check that an integer is greater than or equal to a value * * @param value value * @param minimumValue minimumValue */ public static void isGreaterThanOrEqualTo(int value, int minimumValue, String message) { if (value < minimumValue) { throw new IllegalArgumentException(message); } } }
if (object == null) { throw new IllegalArgumentException(message); }
509
24
533
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_common/src/main/java/io/prometheus/jmx/common/yaml/YamlMapAccessor.java
YamlMapAccessor
getOrCreate
class YamlMapAccessor { private final Map<Object, Object> map; /** * Constructor * * @param map map */ public YamlMapAccessor(Map<Object, Object> map) { if (map == null) { throw new IllegalArgumentException("Map is null"); } this.map = map; } /** * Method to determine if a path exists * * @param path path * @return true if the path exists (but could be null), false otherwise */ public boolean containsPath(String path) { if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } path = validatePath(path); if (path.equals("/")) { return true; } String[] pathTokens = path.split(Pattern.quote("/")); Map<Object, Object> subMap = map; for (int i = 1; i < pathTokens.length; i++) { try { if (subMap.containsKey(pathTokens[i])) { subMap = (Map<Object, Object>) subMap.get(pathTokens[i]); } else { return false; } } catch (NullPointerException | ClassCastException e) { return false; } } return true; } /** * Method to get a path Object * * @param path path * @return an Optional containing the path Object or an empty Optional if the path doesn't exist */ public Optional<Object> get(String path) { if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } path = validatePath(path); if (path.equals("/")) { return Optional.of(map); } String[] pathTokens = path.split(Pattern.quote("/")); Object object = map; for (int i = 1; i < pathTokens.length; i++) { try { object = resolve(pathTokens[i], object); } catch (NullPointerException | ClassCastException e) { return Optional.empty(); } } return Optional.ofNullable(object); } /** * Method to get a path Object or create an Object using the Supplier * * <p>parent paths will be created if required * * @param path path * @return an Optional containing the path Object or Optional created by the Supplier */ public Optional<Object> getOrCreate(String path, Supplier<Object> supplier) {<FILL_FUNCTION_BODY>} /** * Method to get a path Object, throwing an RuntimeException created by the Supplier if the path * doesn't exist * * @param path path * @return an Optional containing the path Object */ public Optional<Object> getOrThrow(String path, Supplier<? extends RuntimeException> supplier) { if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } if (supplier == null) { throw new IllegalArgumentException("supplier is null"); } path = validatePath(path); if (path.equals("/")) { return Optional.of(map); } String[] pathTokens = path.split(Pattern.quote("/")); Object object = map; for (int i = 1; i < pathTokens.length; i++) { try { object = resolve(pathTokens[i], object); } catch (NullPointerException | ClassCastException e) { throw supplier.get(); } if (object == null) { throw supplier.get(); } } return Optional.of(object); } /** * Method to get a MapAccessor backed by an empty Map * * @return the return value */ public static YamlMapAccessor empty() { return new YamlMapAccessor(new LinkedHashMap<>()); } /** * Method to validate a path * * @param path path * @return the return value */ private String validatePath(String path) { if (path == null) { throw new IllegalArgumentException("path is null"); } if (path.equals("/")) { return path; } path = path.trim(); if (path.isEmpty()) { throw new IllegalArgumentException("path is empty"); } if (!path.startsWith("/")) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } if (path.endsWith("/")) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } return path; } /** * Method to resolve a path token to an Object * * @param pathToken pathToken * @param object object * @return the return value * @param <T> the return type */ private <T> T resolve(String pathToken, Object object) { return (T) ((Map<String, Object>) object).get(pathToken); } /** * Method to flatten an array of path tokens to a path * * @param pathTokens pathTokens * @param begin begin * @param end end * @return the return value */ private String flatten(String[] pathTokens, int begin, int end) { StringBuilder stringBuilder = new StringBuilder(); for (int i = begin; i < end; i++) { stringBuilder.append("/").append(pathTokens[i]); } return stringBuilder.toString(); } }
if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException(String.format("path [%s] is invalid", path)); } path = validatePath(path); if (path.equals("/")) { return Optional.of(map); } if (supplier == null) { throw new IllegalArgumentException("supplier is null"); } String[] pathTokens = path.split(Pattern.quote("/")); Object previous = map; Object current = null; for (int i = 1; i < pathTokens.length; i++) { try { current = resolve(pathTokens[i], previous); if (current == null) { if ((i + 1) == pathTokens.length) { Object object = supplier.get(); ((Map<String, Object>) previous).put(pathTokens[i], object); return Optional.of(object); } else { current = new LinkedHashMap<>(); ((Map<String, Object>) previous).put(pathTokens[i], current); } } previous = current; } catch (NullPointerException e) { return Optional.empty(); } catch (ClassCastException e) { if ((i + 1) == pathTokens.length) { throw new IllegalArgumentException( String.format("path [%s] isn't a Map", flatten(pathTokens, 1, i))); } return Optional.empty(); } } return Optional.ofNullable(current);
1,513
394
1,907
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_httpserver/src/main/java/io/prometheus/jmx/WebServer.java
WebServer
main
class WebServer { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd | HH:mm:ss.SSS", Locale.getDefault()); public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (args.length < 2) { System.err.println("Usage: WebServer <[hostname:]port> <yaml configuration file>"); System.exit(1); } String host = "0.0.0.0"; int port; int colonIndex = args[0].lastIndexOf(':'); if (colonIndex < 0) { port = Integer.parseInt(args[0]); } else { port = Integer.parseInt(args[0].substring(colonIndex + 1)); host = args[0].substring(0, colonIndex); } new BuildInfoMetrics().register(PrometheusRegistry.defaultRegistry); new JmxCollector(new File(args[1]), JmxCollector.Mode.STANDALONE) .register(PrometheusRegistry.defaultRegistry); HTTPServer httpServer = null; try { httpServer = new HTTPServerFactory() .createHTTPServer( InetAddress.getByName(host), port, PrometheusRegistry.defaultRegistry, new File(args[1])); System.out.println( String.format( "%s | %s | INFO | %s | %s", SIMPLE_DATE_FORMAT.format(new Date()), Thread.currentThread().getName(), WebServer.class.getName(), "Running")); Thread.currentThread().join(); } catch (ConfigurationException e) { System.err.println("Configuration Exception : " + e.getMessage()); System.exit(1); } catch (Throwable t) { System.err.println("Exception starting"); t.printStackTrace(); } finally { if (httpServer != null) { httpServer.close(); } }
81
463
544
<no_super_class>
prometheus_jmx_exporter
jmx_exporter/jmx_prometheus_javaagent/src/main/java/io/prometheus/jmx/JavaAgent.java
JavaAgent
parseConfig
class JavaAgent { public static final String CONFIGURATION_REGEX = "^(?:((?:[\\w.-]+)|(?:\\[.+])):)?" + // host name, or ipv4, or ipv6 address in brackets "(\\d{1,5}):" + // port "(.+)"; // config file private static final String DEFAULT_HOST = "0.0.0.0"; private static HTTPServer httpServer; public static void agentmain(String agentArgument, Instrumentation instrumentation) throws Exception { premain(agentArgument, instrumentation); } public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { try { Config config = parseConfig(agentArgument); new BuildInfoMetrics().register(PrometheusRegistry.defaultRegistry); JvmMetrics.builder().register(PrometheusRegistry.defaultRegistry); new JmxCollector(new File(config.file), JmxCollector.Mode.AGENT) .register(PrometheusRegistry.defaultRegistry); String host = config.host != null ? config.host : DEFAULT_HOST; httpServer = new HTTPServerFactory() .createHTTPServer( InetAddress.getByName(host), config.port, PrometheusRegistry.defaultRegistry, new File(config.file)); } catch (Throwable t) { synchronized (System.err) { System.err.println("Failed to start Prometheus JMX Exporter"); System.err.println(); t.printStackTrace(); System.err.println(); System.err.println("Prometheus JMX Exporter exiting"); System.err.flush(); } System.exit(1); } } /** * Parse the Java Agent configuration. The arguments are typically specified to the JVM as a * javaagent as {@code -javaagent:/path/to/agent.jar=<CONFIG>}. This method parses the {@code * <CONFIG>} portion. * * @param args provided agent args * @return configuration to use for our application */ private static Config parseConfig(String args) {<FILL_FUNCTION_BODY>} private static class Config { String host; int port; String file; Config(String host, int port, String file) { this.host = host; this.port = port; this.file = file; } } }
Pattern pattern = Pattern.compile(CONFIGURATION_REGEX); Matcher matcher = pattern.matcher(args); if (!matcher.matches()) { System.err.println( "Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration" + " file> "); throw new ConfigurationException("Malformed arguments - " + args); } String givenHost = matcher.group(1); String givenPort = matcher.group(2); String givenConfigFile = matcher.group(3); int port = Integer.parseInt(givenPort); return new Config(givenHost, port, givenConfigFile);
654
181
835
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/ServerMain.java
ServerMain
main
class ServerMain { private static final Logger logger = LoggerFactory.getLogger(ServerMain.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = new SpringApplicationBuilder(ServerMain.class) .logStartupInfo(false) .run(args); stopWatch.stop(); ServerProperties serverProperties = context.getBean(ServerProperties.class); Integer port = serverProperties.getPort(); ServerProperties.Servlet servlet = serverProperties.getServlet(); String contextPath = servlet.getContextPath(); String urlSuffix = StringUtils.isBlank(contextPath)? String.valueOf(port):port+contextPath; logger.info("kkFileView 服务启动完成,耗时:{}s,演示页请访问: http://127.0.0.1:{} ", stopWatch.getTotalTimeSeconds(), urlSuffix);
55
204
259
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/config/RedissonConfig.java
RedissonConfig
config
class RedissonConfig { private String address; private int connectionMinimumIdleSize = 10; private int idleConnectionTimeout=10000; private int pingTimeout=1000; private int connectTimeout=10000; private int timeout=3000; private int retryAttempts=3; private int retryInterval=1500; private int reconnectionTimeout=3000; private int failedAttempts=3; private String password = null; private int subscriptionsPerConnection=5; private String clientName=null; private int subscriptionConnectionMinimumIdleSize = 1; private int subscriptionConnectionPoolSize = 50; private int connectionPoolSize = 64; private int database = 0; private boolean dnsMonitoring = false; private int dnsMonitoringInterval = 5000; private int thread; //当前处理核数量 * 2 private String codec="org.redisson.codec.JsonJacksonCodec"; @Bean Config config() throws Exception {<FILL_FUNCTION_BODY>} public int getThread() { return thread; } public void setThread(int thread) { this.thread = thread; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getIdleConnectionTimeout() { return idleConnectionTimeout; } public void setIdleConnectionTimeout(int idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; } public int getPingTimeout() { return pingTimeout; } public void setPingTimeout(int pingTimeout) { this.pingTimeout = pingTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getRetryAttempts() { return retryAttempts; } public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } public int getRetryInterval() { return retryInterval; } public void setRetryInterval(int retryInterval) { this.retryInterval = retryInterval; } public int getReconnectionTimeout() { return reconnectionTimeout; } public void setReconnectionTimeout(int reconnectionTimeout) { this.reconnectionTimeout = reconnectionTimeout; } public int getFailedAttempts() { return failedAttempts; } public void setFailedAttempts(int failedAttempts) { this.failedAttempts = failedAttempts; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSubscriptionsPerConnection() { return subscriptionsPerConnection; } public void setSubscriptionsPerConnection(int subscriptionsPerConnection) { this.subscriptionsPerConnection = subscriptionsPerConnection; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public int getSubscriptionConnectionMinimumIdleSize() { return subscriptionConnectionMinimumIdleSize; } public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) { this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; } public int getSubscriptionConnectionPoolSize() { return subscriptionConnectionPoolSize; } public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) { this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; } public int getConnectionMinimumIdleSize() { return connectionMinimumIdleSize; } public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) { this.connectionMinimumIdleSize = connectionMinimumIdleSize; } public int getConnectionPoolSize() { return connectionPoolSize; } public void setConnectionPoolSize(int connectionPoolSize) { this.connectionPoolSize = connectionPoolSize; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public boolean isDnsMonitoring() { return dnsMonitoring; } public void setDnsMonitoring(boolean dnsMonitoring) { this.dnsMonitoring = dnsMonitoring; } public int getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(int dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } }
Config config = new Config(); config.useSingleServer().setAddress(address) .setConnectionMinimumIdleSize(connectionMinimumIdleSize) .setConnectionPoolSize(connectionPoolSize) .setDatabase(database) .setDnsMonitoring(dnsMonitoring) .setDnsMonitoringInterval(dnsMonitoringInterval) .setSubscriptionConnectionMinimumIdleSize(subscriptionConnectionMinimumIdleSize) .setSubscriptionConnectionPoolSize(subscriptionConnectionPoolSize) .setSubscriptionsPerConnection(subscriptionsPerConnection) .setClientName(clientName) .setFailedAttempts(failedAttempts) .setRetryAttempts(retryAttempts) .setRetryInterval(retryInterval) .setReconnectionTimeout(reconnectionTimeout) .setTimeout(timeout) .setConnectTimeout(connectTimeout) .setIdleConnectionTimeout(idleConnectionTimeout) .setPingTimeout(pingTimeout) .setPassword(StringUtils.trimToNull(password)); Codec codec=(Codec) ClassUtils.forName(getCodec(), ClassUtils.getDefaultClassLoader()).newInstance(); config.setCodec(codec); config.setThreads(thread); config.setEventLoopGroup(new NioEventLoopGroup()); config.setUseLinuxNativeEpoll(false); return config;
1,395
351
1,746
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/config/WebConfig.java
WebConfig
getBaseUrlFilter
class WebConfig implements WebMvcConfigurer { private final static Logger LOGGER = LoggerFactory.getLogger(WebConfig.class); /** * 访问外部文件配置 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { String filePath = ConfigConstants.getFileDir(); LOGGER.info("Add resource locations: {}", filePath); registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/","file:" + filePath); } @Bean public FilterRegistrationBean<ChinesePathFilter> getChinesePathFilter() { ChinesePathFilter filter = new ChinesePathFilter(); FilterRegistrationBean<ChinesePathFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setOrder(10); return registrationBean; } @Bean public FilterRegistrationBean<TrustHostFilter> getTrustHostFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); filterUri.add("/getCorsFile"); TrustHostFilter filter = new TrustHostFilter(); FilterRegistrationBean<TrustHostFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } @Bean public FilterRegistrationBean<TrustDirFilter> getTrustDirFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); filterUri.add("/getCorsFile"); TrustDirFilter filter = new TrustDirFilter(); FilterRegistrationBean<TrustDirFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } @Bean public FilterRegistrationBean<BaseUrlFilter> getBaseUrlFilter() {<FILL_FUNCTION_BODY>} @Bean public FilterRegistrationBean<UrlCheckFilter> getUrlCheckFilter() { UrlCheckFilter filter = new UrlCheckFilter(); FilterRegistrationBean<UrlCheckFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setOrder(30); return registrationBean; } @Bean public FilterRegistrationBean<AttributeSetFilter> getWatermarkConfigFilter() { Set<String> filterUri = new HashSet<>(); filterUri.add("/index"); filterUri.add("/"); filterUri.add("/onlinePreview"); filterUri.add("/picturesPreview"); AttributeSetFilter filter = new AttributeSetFilter(); FilterRegistrationBean<AttributeSetFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); return registrationBean; } }
Set<String> filterUri = new HashSet<>(); BaseUrlFilter filter = new BaseUrlFilter(); FilterRegistrationBean<BaseUrlFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(filter); registrationBean.setUrlPatterns(filterUri); registrationBean.setOrder(20); return registrationBean;
794
90
884
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/CompressFileReader.java
CompressFileReader
unRar
class CompressFileReader { private final FileHandlerService fileHandlerService; private static final String fileDir = ConfigConstants.getFileDir(); public CompressFileReader(FileHandlerService fileHandlerService) { this.fileHandlerService = fileHandlerService; } public String unRar(String filePath, String filePassword, String fileName, FileAttribute fileAttribute) throws Exception {<FILL_FUNCTION_BODY>} }
List<String> imgUrls = new ArrayList<>(); String baseUrl = BaseUrlFilter.getBaseUrl(); String packagePath = "_"; //防止文件名重复 压缩包统一生成文件添加_符号 String folderName = filePath.replace(fileDir, ""); //修复压缩包 多重目录获取路径错误 if (fileAttribute.isCompressFile()) { //压缩包文件 直接赋予路径 不予下载 folderName = "_decompression" + folderName; //重新修改多重压缩包 生成文件路径 } RandomAccessFile randomAccessFile = null; IInArchive inArchive = null; try { randomAccessFile = new RandomAccessFile(filePath, "r"); inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile)); ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); final String[] str = {null}; for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { if (!item.isFolder()) { ExtractOperationResult result; String finalFolderName = folderName; result = item.extractSlow(data -> { try { str[0] = RarUtils.getUtf8String(item.getPath()); if (RarUtils.isMessyCode(str[0])) { str[0] = new String(item.getPath().getBytes(StandardCharsets.ISO_8859_1), "gbk"); } str[0] = str[0].replace("\\", File.separator); //Linux 下路径错误 String str1 = str[0].substring(0, str[0].lastIndexOf(File.separator) + 1); File file = new File(fileDir, finalFolderName + packagePath + File.separator + str1); if (!file.exists()) { file.mkdirs(); } OutputStream out = new FileOutputStream(fileDir + finalFolderName + packagePath + File.separator + str[0], true); IOUtils.write(data, out); out.close(); } catch (Exception e) { e.printStackTrace(); return Integer.parseInt(null); } return data.length; }, filePassword); if (result == ExtractOperationResult.OK) { FileType type = FileType.typeFromUrl(str[0]); if (type.equals(FileType.PICTURE)) { imgUrls.add(baseUrl + folderName + packagePath + "/" + str[0].replace("\\", "/")); } fileHandlerService.putImgCache(fileName + packagePath, imgUrls); } else { return null; } } } return folderName + packagePath; } catch (Exception e) { throw new Exception(e); } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { System.err.println("Error closing archive: " + e); } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { System.err.println("Error closing file: " + e); } } }
110
867
977
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/FileConvertQueueTask.java
ConvertTask
run
class ConvertTask implements Runnable { private final Logger logger = LoggerFactory.getLogger(ConvertTask.class); private final FilePreviewFactory previewFactory; private final CacheService cacheService; private final FileHandlerService fileHandlerService; public ConvertTask(FilePreviewFactory previewFactory, CacheService cacheService, FileHandlerService fileHandlerService) { this.previewFactory = previewFactory; this.cacheService = cacheService; this.fileHandlerService = fileHandlerService; } @Override public void run() {<FILL_FUNCTION_BODY>} public boolean isNeedConvert(FileType fileType) { return fileType.equals(FileType.COMPRESS) || fileType.equals(FileType.OFFICE) || fileType.equals(FileType.CAD); } }
while (true) { String url = null; try { url = cacheService.takeQueueTask(); if (url != null) { FileAttribute fileAttribute = fileHandlerService.getFileAttribute(url, null); FileType fileType = fileAttribute.getType(); logger.info("正在处理预览转换任务,url:{},预览类型:{}", url, fileType); if (isNeedConvert(fileType)) { FilePreview filePreview = previewFactory.get(fileAttribute); filePreview.filePreviewHandle(url, new ExtendedModelMap(), fileAttribute); } else { logger.info("预览类型无需处理,url:{},预览类型:{}", url, fileType); } } } catch (Exception e) { try { TimeUnit.SECONDS.sleep(10); } catch (Exception ex) { Thread.currentThread().interrupt(); ex.printStackTrace(); } logger.info("处理预览转换任务异常,url:{}", url, e); } }
212
283
495
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/OfficePluginManager.java
OfficePluginManager
killProcess
class OfficePluginManager { private final Logger logger = LoggerFactory.getLogger(OfficePluginManager.class); private LocalOfficeManager officeManager; @Value("${office.plugin.server.ports:2001,2002}") private String serverPorts; @Value("${office.plugin.task.timeout:5m}") private String timeOut; @Value("${office.plugin.task.taskexecutiontimeout:5m}") private String taskExecutionTimeout; @Value("${office.plugin.task.maxtasksperprocess:5}") private int maxTasksPerProcess; /** * 启动Office组件进程 */ @PostConstruct public void startOfficeManager() throws OfficeException { File officeHome = LocalOfficeUtils.getDefaultOfficeHome(); if (officeHome == null) { throw new RuntimeException("找不到office组件,请确认'office.home'配置是否有误"); } boolean killOffice = killProcess(); if (killOffice) { logger.warn("检测到有正在运行的office进程,已自动结束该进程"); } try { String[] portsString = serverPorts.split(","); int[] ports = Arrays.stream(portsString).mapToInt(Integer::parseInt).toArray(); long timeout = DurationStyle.detectAndParse(timeOut).toMillis(); long taskexecutiontimeout = DurationStyle.detectAndParse(taskExecutionTimeout).toMillis(); officeManager = LocalOfficeManager.builder() .officeHome(officeHome) .portNumbers(ports) .processTimeout(timeout) .maxTasksPerProcess(maxTasksPerProcess) .taskExecutionTimeout(taskexecutiontimeout) .build(); officeManager.start(); InstalledOfficeManagerHolder.setInstance(officeManager); } catch (Exception e) { logger.error("启动office组件失败,请检查office组件是否可用"); throw e; } } private boolean killProcess() {<FILL_FUNCTION_BODY>} @PreDestroy public void destroyOfficeManager() { if (null != officeManager && officeManager.isRunning()) { logger.info("Shutting down office process"); OfficeUtils.stopQuietly(officeManager); } } }
boolean flag = false; try { if (OSUtils.IS_OS_WINDOWS) { Process p = Runtime.getRuntime().exec("cmd /c tasklist "); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (s.contains("soffice.bin")) { Runtime.getRuntime().exec("taskkill /im " + "soffice.bin" + " /f"); flag = true; } } else if (OSUtils.IS_OS_MAC || OSUtils.IS_OS_MAC_OSX) { Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", "ps -ef | grep " + "soffice.bin"}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (StringUtils.ordinalIndexOf(s, "soffice.bin", 3) > 0) { String[] cmd = {"sh", "-c", "kill -15 `ps -ef|grep " + "soffice.bin" + "|awk 'NR==1{print $2}'`"}; Runtime.getRuntime().exec(cmd); flag = true; } } else { Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", "ps -ef | grep " + "soffice.bin" + " |grep -v grep | wc -l"}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } String s = baos.toString(); if (!s.startsWith("0")) { String[] cmd = {"sh", "-c", "ps -ef | grep soffice.bin | grep -v grep | awk '{print \"kill -9 \"$2}' | sh"}; Runtime.getRuntime().exec(cmd); flag = true; } } } catch (IOException e) { logger.error("检测office进程异常", e); } return flag;
611
649
1,260
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/OfficeToPdfService.java
OfficeToPdfService
converterFile
class OfficeToPdfService { private final static Logger logger = LoggerFactory.getLogger(OfficeToPdfService.class); public void openOfficeToPDF(String inputFilePath, String outputFilePath, FileAttribute fileAttribute) throws OfficeException { office2pdf(inputFilePath, outputFilePath, fileAttribute); } public static void converterFile(File inputFile, String outputFilePath_end, FileAttribute fileAttribute) throws OfficeException {<FILL_FUNCTION_BODY>} public void office2pdf(String inputFilePath, String outputFilePath, FileAttribute fileAttribute) throws OfficeException { if (null != inputFilePath) { File inputFile = new File(inputFilePath); // 判断目标文件路径是否为空 if (null == outputFilePath) { // 转换后的文件路径 String outputFilePath_end = getOutputFilePath(inputFilePath); if (inputFile.exists()) { // 找不到源文件, 则返回 converterFile(inputFile, outputFilePath_end, fileAttribute); } } else { if (inputFile.exists()) { // 找不到源文件, 则返回 converterFile(inputFile, outputFilePath, fileAttribute); } } } } public static String getOutputFilePath(String inputFilePath) { return inputFilePath.replaceAll("."+ getPostfix(inputFilePath), ".pdf"); } public static String getPostfix(String inputFilePath) { return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1); } }
File outputFile = new File(outputFilePath_end); // 假如目标路径不存在,则新建该路径 if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { logger.error("创建目录【{}】失败,请检查目录权限!",outputFilePath_end); } LocalConverter.Builder builder; Map<String, Object> filterData = new HashMap<>(); filterData.put("EncryptFile", true); if(!ConfigConstants.getOfficePageRange().equals("false")){ filterData.put("PageRange", ConfigConstants.getOfficePageRange()); //限制页面 } if(!ConfigConstants.getOfficeWatermark().equals("false")){ filterData.put("Watermark", ConfigConstants.getOfficeWatermark()); //水印 } filterData.put("Quality", ConfigConstants.getOfficeQuality()); //图片压缩 filterData.put("MaxImageResolution", ConfigConstants.getOfficeMaxImageResolution()); //DPI if(ConfigConstants.getOfficeExportBookmarks()){ filterData.put("ExportBookmarks", true); //导出书签 } if(ConfigConstants.getOfficeExportNotes()){ filterData.put("ExportNotes", true); //批注作为PDF的注释 } if(ConfigConstants.getOfficeDocumentOpenPasswords()){ filterData.put("DocumentOpenPassword", fileAttribute.getFilePassword()); //给PDF添加密码 } Map<String, Object> customProperties = new HashMap<>(); customProperties.put("FilterData", filterData); if (StringUtils.isNotBlank(fileAttribute.getFilePassword())) { Map<String, Object> loadProperties = new HashMap<>(); loadProperties.put("Hidden", true); loadProperties.put("ReadOnly", true); loadProperties.put("UpdateDocMode", UpdateDocMode.NO_UPDATE); loadProperties.put("Password", fileAttribute.getFilePassword()); builder = LocalConverter.builder().loadProperties(loadProperties).storeProperties(customProperties); } else { builder = LocalConverter.builder().storeProperties(customProperties); } builder.build().convert(inputFile).to(outputFile).execute();
414
564
978
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/CadFilePreviewImpl.java
CadFilePreviewImpl
filePreviewHandle
class CadFilePreviewImpl implements FilePreview { private static final String OFFICE_PREVIEW_TYPE_IMAGE = "image"; private static final String OFFICE_PREVIEW_TYPE_ALL_IMAGES = "allImages"; private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; public CadFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
// 预览Type,参数传了就取参数的,没传取系统默认 String officePreviewType = fileAttribute.getOfficePreviewType() == null ? ConfigConstants.getOfficePreviewType() : fileAttribute.getOfficePreviewType(); String baseUrl = BaseUrlFilter.getBaseUrl(); boolean forceUpdatedCache = fileAttribute.forceUpdatedCache(); String fileName = fileAttribute.getName(); String cadPreviewType = ConfigConstants.getCadPreviewType(); String cacheName = fileAttribute.getCacheName(); String outFilePath = fileAttribute.getOutFilePath(); // 判断之前是否已转换过,如果转换过,直接返回,否则执行转换 if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } String filePath = response.getContent(); String imageUrls = null; if (StringUtils.hasText(outFilePath)) { try { imageUrls = fileHandlerService.cadToPdf(filePath, outFilePath, cadPreviewType, fileAttribute); } catch (Exception e) { e.printStackTrace(); } if (imageUrls == null) { return otherFilePreview.notSupportedFile(model, fileAttribute, "CAD转换异常,请联系管理员"); } //是否保留CAD源文件 if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) { KkFileUtils.deleteFileByPath(filePath); } if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath)); } } } cacheName= WebUtils.encodeFileName(cacheName); if ("tif".equalsIgnoreCase(cadPreviewType)) { model.addAttribute("currentUrl", cacheName); return TIFF_FILE_PREVIEW_PAGE; } else if ("svg".equalsIgnoreCase(cadPreviewType)) { model.addAttribute("currentUrl", cacheName); return SVG_FILE_PREVIEW_PAGE; } if (baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) { return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath, fileHandlerService, OFFICE_PREVIEW_TYPE_IMAGE, otherFilePreview); } model.addAttribute("pdfUrl", cacheName); return PDF_FILE_PREVIEW_PAGE;
182
741
923
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/CommonPreviewImpl.java
CommonPreviewImpl
filePreviewHandle
class CommonPreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; public CommonPreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
// 不是http开头,浏览器不能直接访问,需下载到本地 if (url != null && !url.toLowerCase().startsWith("http")) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, null); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } else { String file = fileHandlerService.getRelativePath(response.getContent()); model.addAttribute("currentUrl", file); } } else { model.addAttribute("currentUrl", url); } return null;
133
167
300
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/CompressFilePreviewImpl.java
CompressFilePreviewImpl
filePreviewHandle
class CompressFilePreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final CompressFileReader compressFileReader; private final OtherFilePreviewImpl otherFilePreview; private static final String Rar_PASSWORD_MSG = "password"; public CompressFilePreviewImpl(FileHandlerService fileHandlerService, CompressFileReader compressFileReader, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.compressFileReader = compressFileReader; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
String fileName=fileAttribute.getName(); String filePassword = fileAttribute.getFilePassword(); boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); String fileTree = null; // 判断文件名是否存在(redis缓存读取) if (forceUpdatedCache || !StringUtils.hasText(fileHandlerService.getConvertedFile(fileName)) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } String filePath = response.getContent(); try { fileTree = compressFileReader.unRar(filePath, filePassword,fileName, fileAttribute); } catch (Exception e) { Throwable[] throwableArray = ExceptionUtils.getThrowables(e); for (Throwable throwable : throwableArray) { if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) { if (e.getMessage().toLowerCase().contains(Rar_PASSWORD_MSG)) { model.addAttribute("needFilePassword", true); return EXEL_FILE_PREVIEW_PAGE; } } } } if (!ObjectUtils.isEmpty(fileTree)) { //是否保留压缩包源文件 if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) { KkFileUtils.deleteFileByPath(filePath); } if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(fileName, fileTree); } }else { return otherFilePreview.notSupportedFile(model, fileAttribute, "压缩文件密码错误! 压缩文件损坏! 压缩文件类型不受支持!"); } } else { fileTree = fileHandlerService.getConvertedFile(fileName); } model.addAttribute("fileName", fileName); model.addAttribute("fileTree", fileTree); return COMPRESS_FILE_PREVIEW_PAGE;
187
546
733
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/MediaFilePreviewImpl.java
MediaFilePreviewImpl
convertToMp4
class MediaFilePreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; private static final String mp4 = "mp4"; public MediaFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { String fileName = fileAttribute.getName(); String suffix = fileAttribute.getSuffix(); String cacheName = fileAttribute.getCacheName(); String outFilePath = fileAttribute.getOutFilePath(); boolean forceUpdatedCache = fileAttribute.forceUpdatedCache(); FileType type = fileAttribute.getType(); String[] mediaTypesConvert = FileType.MEDIA_CONVERT_TYPES; //获取支持的转换格式 boolean mediaTypes = false; for (String temp : mediaTypesConvert) { if (suffix.equals(temp)) { mediaTypes = true; break; } } if (!url.toLowerCase().startsWith("http") || checkNeedConvert(mediaTypes)) { //不是http协议的 // 开启转换方式并是支持转换格式的 if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) { //查询是否开启缓存 ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } String filePath = response.getContent(); String convertedUrl = null; try { if (mediaTypes) { convertedUrl = convertToMp4(filePath, outFilePath, fileAttribute); } else { convertedUrl = outFilePath; //其他协议的 不需要转换方式的文件 直接输出 } } catch (Exception e) { e.printStackTrace(); } if (convertedUrl == null) { return otherFilePreview.notSupportedFile(model, fileAttribute, "视频转换异常,请联系管理员"); } if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath)); } model.addAttribute("mediaUrl", fileHandlerService.getRelativePath(outFilePath)); } else { model.addAttribute("mediaUrl", fileHandlerService.listConvertedFiles().get(cacheName)); } return MEDIA_FILE_PREVIEW_PAGE; } if (type.equals(FileType.MEDIA)) { // 支持输出 只限默认格式 model.addAttribute("mediaUrl", url); return MEDIA_FILE_PREVIEW_PAGE; } return otherFilePreview.notSupportedFile(model, fileAttribute, "系统还不支持该格式文件的在线预览"); } /** * 检查视频文件转换是否已开启,以及当前文件是否需要转换 * * @return */ private boolean checkNeedConvert(boolean mediaTypes) { //1.检查开关是否开启 if ("true".equals(ConfigConstants.getMediaConvertDisable())) { return mediaTypes; } return false; } private static String convertToMp4(String filePath, String outFilePath, FileAttribute fileAttribute) throws Exception {<FILL_FUNCTION_BODY>} }
FFmpegFrameGrabber frameGrabber = FFmpegFrameGrabber.createDefault(filePath); Frame captured_frame; FFmpegFrameRecorder recorder = null; try { File desFile = new File(outFilePath); //判断一下防止重复转换 if (desFile.exists()) { return outFilePath; } if (fileAttribute.isCompressFile()) { //判断 是压缩包的创建新的目录 int index = outFilePath.lastIndexOf("/"); //截取最后一个斜杠的前面的内容 String folder = outFilePath.substring(0, index); File path = new File(folder); //目录不存在 创建新的目录 if (!path.exists()) { path.mkdirs(); } } frameGrabber.start(); recorder = new FFmpegFrameRecorder(outFilePath, frameGrabber.getImageWidth(), frameGrabber.getImageHeight(), frameGrabber.getAudioChannels()); // recorder.setImageHeight(640); // recorder.setImageWidth(480); recorder.setFormat(mp4); recorder.setFrameRate(frameGrabber.getFrameRate()); recorder.setSampleRate(frameGrabber.getSampleRate()); //视频编码属性配置 H.264 H.265 MPEG recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //设置视频比特率,单位:b recorder.setVideoBitrate(frameGrabber.getVideoBitrate()); recorder.setAspectRatio(frameGrabber.getAspectRatio()); // 设置音频通用编码格式 recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC); //设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 128000 = 182kb) recorder.setAudioBitrate(frameGrabber.getAudioBitrate()); recorder.setAudioOptions(frameGrabber.getAudioOptions()); recorder.setAudioChannels(frameGrabber.getAudioChannels()); recorder.start(); while (true) { captured_frame = frameGrabber.grabFrame(); if (captured_frame == null) { System.out.println("转码完成:" + filePath); break; } recorder.record(captured_frame); } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (recorder != null) { //关闭 recorder.stop(); recorder.close(); } frameGrabber.stop(); frameGrabber.close(); } return outFilePath;
939
750
1,689
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/OfficeFilePreviewImpl.java
OfficeFilePreviewImpl
filePreviewHandle
class OfficeFilePreviewImpl implements FilePreview { public static final String OFFICE_PREVIEW_TYPE_IMAGE = "image"; public static final String OFFICE_PREVIEW_TYPE_ALL_IMAGES = "allImages"; private static final String OFFICE_PASSWORD_MSG = "password"; private final FileHandlerService fileHandlerService; private final OfficeToPdfService officeToPdfService; private final OtherFilePreviewImpl otherFilePreview; public OfficeFilePreviewImpl(FileHandlerService fileHandlerService, OfficeToPdfService officeToPdfService, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.officeToPdfService = officeToPdfService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} static String getPreviewType(Model model, FileAttribute fileAttribute, String officePreviewType, String pdfName, String outFilePath, FileHandlerService fileHandlerService, String officePreviewTypeImage, OtherFilePreviewImpl otherFilePreview) { String suffix = fileAttribute.getSuffix(); boolean isPPT = suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx"); List<String> imageUrls = null; try { imageUrls = fileHandlerService.pdf2jpg(outFilePath,outFilePath, pdfName, fileAttribute); } catch (Exception e) { Throwable[] throwableArray = ExceptionUtils.getThrowables(e); for (Throwable throwable : throwableArray) { if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) { if (e.getMessage().toLowerCase().contains(OFFICE_PASSWORD_MSG)) { model.addAttribute("needFilePassword", true); return EXEL_FILE_PREVIEW_PAGE; } } } } if (imageUrls == null || imageUrls.size() < 1) { return otherFilePreview.notSupportedFile(model, fileAttribute, "office转图片异常,请联系管理员"); } model.addAttribute("imgUrls", imageUrls); model.addAttribute("currentUrl", imageUrls.get(0)); if (officePreviewTypeImage.equals(officePreviewType)) { // PPT 图片模式使用专用预览页面 return (isPPT ? PPT_FILE_PREVIEW_PAGE : OFFICE_PICTURE_FILE_PREVIEW_PAGE); } else { return PICTURE_FILE_PREVIEW_PAGE; } } }
// 预览Type,参数传了就取参数的,没传取系统默认 String officePreviewType = fileAttribute.getOfficePreviewType(); boolean userToken = fileAttribute.getUsePasswordCache(); String baseUrl = BaseUrlFilter.getBaseUrl(); String suffix = fileAttribute.getSuffix(); //获取文件后缀 String fileName = fileAttribute.getName(); //获取文件原始名称 String filePassword = fileAttribute.getFilePassword(); //获取密码 boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令 boolean isHtmlView = fileAttribute.isHtmlView(); //xlsx 转换成html String cacheName = fileAttribute.getCacheName(); //转换后的文件名 String outFilePath = fileAttribute.getOutFilePath(); //转换后生成文件的路径 if (!officePreviewType.equalsIgnoreCase("html")) { if (ConfigConstants.getOfficeTypeWeb() .equalsIgnoreCase("web")) { if (suffix.equalsIgnoreCase("xlsx")) { model.addAttribute("pdfUrl", KkFileUtils.htmlEscape(url)); //特殊符号处理 return XLSX_FILE_PREVIEW_PAGE; } if (suffix.equalsIgnoreCase("csv")) { model.addAttribute("csvUrl", KkFileUtils.htmlEscape(url)); return CSV_FILE_PREVIEW_PAGE; } } } if (forceUpdatedCache|| !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) { // 下载远程文件到本地,如果文件在本地已存在不会重复下载 ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } String filePath = response.getContent(); boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath); // 判断是否加密文件 if (isPwdProtectedOffice && !StringUtils.hasLength(filePassword)) { // 加密文件需要密码 model.addAttribute("needFilePassword", true); return EXEL_FILE_PREVIEW_PAGE; } else { if (StringUtils.hasText(outFilePath)) { try { officeToPdfService.openOfficeToPDF(filePath, outFilePath, fileAttribute); } catch (OfficeException e) { if (isPwdProtectedOffice && !OfficeUtils.isCompatible(filePath, filePassword)) { // 加密文件密码错误,提示重新输入 model.addAttribute("needFilePassword", true); model.addAttribute("filePasswordError", true); return EXEL_FILE_PREVIEW_PAGE; } return otherFilePreview.notSupportedFile(model, fileAttribute, "抱歉,该文件版本不兼容,文件版本错误。"); } if (isHtmlView) { // 对转换后的文件进行操作(改变编码方式) fileHandlerService.doActionConvertedFile(outFilePath); } //是否保留OFFICE源文件 if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) { KkFileUtils.deleteFileByPath(filePath); } if (userToken || !isPwdProtectedOffice) { // 加入缓存 fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath)); } } } } if (!isHtmlView && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) { return getPreviewType(model, fileAttribute, officePreviewType, cacheName, outFilePath, fileHandlerService, OFFICE_PREVIEW_TYPE_IMAGE, otherFilePreview); } model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName)); //输出转义文件名 方便url识别 return isHtmlView ? EXEL_FILE_PREVIEW_PAGE : PDF_FILE_PREVIEW_PAGE;
691
1,102
1,793
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/PdfFilePreviewImpl.java
PdfFilePreviewImpl
filePreviewHandle
class PdfFilePreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; private static final String PDF_PASSWORD_MSG = "password"; public PdfFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
String pdfName = fileAttribute.getName(); //获取原始文件名 String officePreviewType = fileAttribute.getOfficePreviewType(); //转换类型 boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令 String outFilePath = fileAttribute.getOutFilePath(); //生成的文件路径 String originFilePath = fileAttribute.getOriginFilePath(); //原始文件路径 if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) { //当文件不存在时,就去下载 if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, pdfName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } originFilePath = response.getContent(); if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(originFilePath)); } } List<String> imageUrls; try { imageUrls = fileHandlerService.pdf2jpg(originFilePath,outFilePath, pdfName, fileAttribute); } catch (Exception e) { Throwable[] throwableArray = ExceptionUtils.getThrowables(e); for (Throwable throwable : throwableArray) { if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) { if (e.getMessage().toLowerCase().contains(PDF_PASSWORD_MSG)) { model.addAttribute("needFilePassword", true); return EXEL_FILE_PREVIEW_PAGE; } } } return otherFilePreview.notSupportedFile(model, fileAttribute, "pdf转图片异常,请联系管理员"); } if (imageUrls == null || imageUrls.size() < 1) { return otherFilePreview.notSupportedFile(model, fileAttribute, "pdf转图片异常,请联系管理员"); } model.addAttribute("imgUrls", imageUrls); model.addAttribute("currentUrl", imageUrls.get(0)); if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) { return OFFICE_PICTURE_FILE_PREVIEW_PAGE; } else { return PICTURE_FILE_PREVIEW_PAGE; } } else { // 不是http开头,浏览器不能直接访问,需下载到本地 if (url != null && !url.toLowerCase().startsWith("http")) { if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, pdfName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } model.addAttribute("pdfUrl", fileHandlerService.getRelativePath(response.getContent())); if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath)); } } else { model.addAttribute("pdfUrl", WebUtils.encodeFileName(pdfName)); } } else { model.addAttribute("pdfUrl", url); } } return PDF_FILE_PREVIEW_PAGE;
152
964
1,116
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/PictureFilePreviewImpl.java
PictureFilePreviewImpl
filePreviewHandle
class PictureFilePreviewImpl extends CommonPreviewImpl { private final FileHandlerService fileHandlerService; public PictureFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) { super(fileHandlerService, otherFilePreview); this.fileHandlerService = fileHandlerService; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
url= KkFileUtils.htmlEscape(url); List<String> imgUrls = new ArrayList<>(); imgUrls.add(url); String compressFileKey = fileAttribute.getCompressFileKey(); List<String> zipImgUrls = fileHandlerService.getImgCache(compressFileKey); if (!CollectionUtils.isEmpty(zipImgUrls)) { imgUrls.addAll(zipImgUrls); } // 不是http开头,浏览器不能直接访问,需下载到本地 super.filePreviewHandle(url, model, fileAttribute); model.addAttribute("imgUrls", imgUrls); return PICTURE_FILE_PREVIEW_PAGE;
123
190
313
<methods>public void <init>(cn.keking.service.FileHandlerService, cn.keking.service.impl.OtherFilePreviewImpl) ,public java.lang.String filePreviewHandle(java.lang.String, Model, cn.keking.model.FileAttribute) <variables>private final non-sealed cn.keking.service.FileHandlerService fileHandlerService,private final non-sealed cn.keking.service.impl.OtherFilePreviewImpl otherFilePreview
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/SimTextFilePreviewImpl.java
SimTextFilePreviewImpl
textData
class SimTextFilePreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; public SimTextFilePreviewImpl(FileHandlerService fileHandlerService,OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { String fileName = fileAttribute.getName(); boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); String filePath = fileAttribute.getOriginFilePath(); if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(fileName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } filePath = response.getContent(); if (ConfigConstants.isCacheEnabled()) { fileHandlerService.addConvertedFile(fileName, filePath); //加入缓存 } try { String fileData = HtmlUtils.htmlEscape(textData(filePath,fileName)); model.addAttribute("textData", Base64.encodeBase64String(fileData.getBytes())); } catch (IOException e) { return otherFilePreview.notSupportedFile(model, fileAttribute, e.getLocalizedMessage()); } return TXT_FILE_PREVIEW_PAGE; } String fileData = null; try { fileData = HtmlUtils.htmlEscape(textData(filePath,fileName)); } catch (IOException e) { e.printStackTrace(); } model.addAttribute("textData", Base64.encodeBase64String(fileData.getBytes())); return TXT_FILE_PREVIEW_PAGE; } private String textData(String filePath,String fileName) throws IOException {<FILL_FUNCTION_BODY>} }
File file = new File(filePath); if (KkFileUtils.isIllegalFileName(fileName)) { return null; } if (!file.exists() || file.length() == 0) { return ""; } else { String charset = EncodingDetects.getJavaEncode(filePath); if ("ASCII".equals(charset)) { charset = StandardCharsets.US_ASCII.name(); } BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset)); StringBuilder result = new StringBuilder(); String line; while ((line = br.readLine()) != null) { result.append(line).append("\r\n"); } br.close(); return result.toString(); }
541
208
749
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/service/impl/TiffFilePreviewImpl.java
TiffFilePreviewImpl
filePreviewHandle
class TiffFilePreviewImpl implements FilePreview { private final FileHandlerService fileHandlerService; private final OtherFilePreviewImpl otherFilePreview; public TiffFilePreviewImpl(FileHandlerService fileHandlerService,OtherFilePreviewImpl otherFilePreview) { this.fileHandlerService = fileHandlerService; this.otherFilePreview = otherFilePreview; } @Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {<FILL_FUNCTION_BODY>} }
String fileName = fileAttribute.getName(); String tifPreviewType = ConfigConstants.getTifPreviewType(); String cacheName = fileAttribute.getCacheName(); String outFilePath = fileAttribute.getOutFilePath(); boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); if ("jpg".equalsIgnoreCase(tifPreviewType) || "pdf".equalsIgnoreCase(tifPreviewType)) { if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } String filePath = response.getContent(); if ("pdf".equalsIgnoreCase(tifPreviewType)) { try { ConvertPicUtil.convertJpg2Pdf(filePath, outFilePath); } catch (Exception e) { if (e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) { model.addAttribute("imgUrls", url); model.addAttribute("currentUrl", url); return PICTURE_FILE_PREVIEW_PAGE; }else { return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转pdf异常,请联系系统管理员!" ); } } //是否保留TIFF源文件 if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) { // KkFileUtils.deleteFileByPath(filePath); } if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath)); } model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName)); return PDF_FILE_PREVIEW_PAGE; }else { // 将tif转换为jpg,返回转换后的文件路径、文件名的list List<String> listPic2Jpg; try { listPic2Jpg = ConvertPicUtil.convertTif2Jpg(filePath, outFilePath,forceUpdatedCache); } catch (Exception e) { if (e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) { model.addAttribute("imgUrls", url); model.addAttribute("currentUrl", url); return PICTURE_FILE_PREVIEW_PAGE; }else { return otherFilePreview.notSupportedFile(model, fileAttribute, "TIF转JPG异常,请联系系统管理员!" ); } } //是否保留源文件,转换失败保留源文件,转换成功删除源文件 if(!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) { KkFileUtils.deleteFileByPath(filePath); } if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.putImgCache(cacheName, listPic2Jpg); fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath)); } model.addAttribute("imgUrls", listPic2Jpg); model.addAttribute("currentUrl", listPic2Jpg.get(0)); return PICTURE_FILE_PREVIEW_PAGE; } } if ("pdf".equalsIgnoreCase(tifPreviewType)) { model.addAttribute("pdfUrl", WebUtils.encodeFileName(cacheName)); return PDF_FILE_PREVIEW_PAGE; } else if ("jpg".equalsIgnoreCase(tifPreviewType)) { model.addAttribute("imgUrls", fileHandlerService.getImgCache(cacheName)); model.addAttribute("currentUrl", fileHandlerService.getImgCache(cacheName).get(0)); return PICTURE_FILE_PREVIEW_PAGE; } } // 不是http开头,浏览器不能直接访问,需下载到本地 if (url != null && !url.toLowerCase().startsWith("http")) { if (forceUpdatedCache || !fileHandlerService.listConvertedFiles().containsKey(fileName) || !ConfigConstants.isCacheEnabled()) { ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName); if (response.isFailure()) { return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg()); } model.addAttribute("currentUrl", fileHandlerService.getRelativePath(response.getContent())); if (ConfigConstants.isCacheEnabled()) { // 加入缓存 fileHandlerService.addConvertedFile(fileName, fileHandlerService.getRelativePath(outFilePath)); } } else { model.addAttribute("currentUrl", WebUtils.encodeFileName(fileName)); } return TIFF_FILE_PREVIEW_PAGE; } model.addAttribute("currentUrl", url); return TIFF_FILE_PREVIEW_PAGE;
135
1,347
1,482
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/CaptchaUtil.java
CaptchaUtil
generateCaptchaPic
class CaptchaUtil { public static final String CAPTCHA_CODE = "captchaCode"; public static final String CAPTCHA_GENERATE_TIME = "captchaTime"; private static final int WIDTH = 100;// 定义图片的width private static final int HEIGHT = 30;// 定义图片的height private static final int CODE_LENGTH = 4;// 定义图片上显示验证码的个数 private static final int FONT_HEIGHT = 28; private static final char[] CODE_SEQUENCE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', '2', '3', '4', '5', '6', '7', '8', '9'}; /** * 指定验证码、生成验证码图片。 * @param captchaCode 验证码 * @return 验证码图片 */ public static BufferedImage generateCaptchaPic(final String captchaCode) {<FILL_FUNCTION_BODY>} /** * 生成随机字符串。 * @return 字符串 */ public static String generateCaptchaCode() { Random random = new Random(); StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < CODE_LENGTH; i++) { randomCode.append(CODE_SEQUENCE[random.nextInt(52)]); } return randomCode.toString(); } }
Assert.notNull(captchaCode, "captchaCode must not be null"); // 定义图像buffer BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics gd = buffImg.getGraphics(); Random random = new Random(); // 将图像填充为白色 gd.setColor(Color.WHITE); gd.fillRect(0, 0, WIDTH, HEIGHT); Font font = new Font("Times New Roman", Font.BOLD, FONT_HEIGHT); gd.setFont(font); // 画边框。 gd.setColor(Color.BLACK); gd.drawRect(0, 0, WIDTH - 1, HEIGHT - 1); // 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。 gd.setColor(Color.BLACK); for (int i = 0; i < 30; i++) { int x = random.nextInt(WIDTH); int y = random.nextInt(HEIGHT); int xl = random.nextInt(12); int yl = random.nextInt(12); gd.drawLine(x, y, x + xl, y + yl); } // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。 int red, green, blue; // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。 red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); // 用随机产生的颜色将验证码绘制到图像中。 gd.setColor(new Color(red, green, blue)); gd.drawString(captchaCode, 18, 27); return buffImg;
499
512
1,011
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/ConfigUtils.java
ConfigUtils
getHomePath
class ConfigUtils { private static final String MAIN_DIRECTORY_NAME = "server"; public static String getHomePath() {<FILL_FUNCTION_BODY>} // 获取环境变量,如果找不到则返回默认值 @SuppressWarnings("SameParameterValue") private static String getEnvOrDefault(String key, String def) { String value = System.getenv(key); return value == null ? def : value; } // 返回参数列表中第一个真实存在的路径,或者 null private static String firstExists(File... paths) { for (File path : paths) { if (path.exists()) { return path.getAbsolutePath(); } } return null; } public static String getUserDir() { String userDir = System.getProperty("user.dir"); String binFolder = getEnvOrDefault("KKFILEVIEW_BIN_FOLDER", userDir); File pluginPath = new File(binFolder); // 如果指定了 bin 或其父目录,则返回父目录 if (new File(pluginPath, "bin").exists()) { return pluginPath.getAbsolutePath(); } else if (pluginPath.exists() && pluginPath.getName().equals("bin")) { return pluginPath.getParentFile().getAbsolutePath(); } else { return firstExists(new File(pluginPath, MAIN_DIRECTORY_NAME), new File(pluginPath.getParentFile(), MAIN_DIRECTORY_NAME)); } } public static String getCustomizedConfigPath() { String homePath = getHomePath(); String separator = java.io.File.separator; return homePath + separator + "config" + separator + "application.properties"; } public synchronized static void restorePropertiesFromEnvFormat(Properties properties) { Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Object, Object> entry = iterator.next(); String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (value.trim().startsWith("${") && value.trim().endsWith("}")) { int beginIndex = value.indexOf(":"); if (beginIndex < 0) { beginIndex = value.length() - 1; } int endIndex = value.length() - 1; String envKey = value.substring(2, beginIndex); String envValue = System.getenv(envKey); if (envValue == null || "".equals(envValue.trim())) { value = value.substring(beginIndex + 1, endIndex); } else { value = envValue; } properties.setProperty(key, value); } } } }
String userDir = System.getenv("KKFILEVIEW_BIN_FOLDER"); if (userDir == null) { userDir = System.getProperty("user.dir"); } if (userDir.endsWith("bin")) { userDir = userDir.substring(0, userDir.length() - 4); } else { String separator = File.separator; if (userDir.endsWith(MAIN_DIRECTORY_NAME)) { userDir = userDir + separator + "src" + separator + "main"; } else { userDir = userDir + separator + MAIN_DIRECTORY_NAME + separator + "src" + separator + "main"; } } return userDir;
740
196
936
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/ConvertPicUtil.java
ConvertPicUtil
convertTif2Jpg
class ConvertPicUtil { private static final int FIT_WIDTH = 500; private static final int FIT_HEIGHT = 900; private final static Logger logger = LoggerFactory.getLogger(ConvertPicUtil.class); private final static String fileDir = ConfigConstants.getFileDir(); /** * Tif 转 JPG。 * * @param strInputFile 输入文件的路径和文件名 * @param strOutputFile 输出文件的路径和文件名 * @return boolean 是否转换成功 */ public static List<String> convertTif2Jpg(String strInputFile, String strOutputFile, boolean forceUpdatedCache) throws Exception {<FILL_FUNCTION_BODY>} /** * 将Jpg图片转换为Pdf文件 * * @param strJpgFile 输入的jpg的路径和文件名 * @param strPdfFile 输出的pdf的路径和文件名 */ public static String convertJpg2Pdf(String strJpgFile, String strPdfFile) throws Exception { Document document = new Document(); RandomAccessFileOrArray rafa = null; FileOutputStream outputStream = null; try { RandomAccessFile aFile = new RandomAccessFile(strJpgFile, "r"); FileChannel inChannel = aFile.getChannel(); FileChannelRandomAccessSource fcra = new FileChannelRandomAccessSource(inChannel); rafa = new RandomAccessFileOrArray(fcra); int pages = TiffImage.getNumberOfPages(rafa); outputStream = new FileOutputStream(strPdfFile); PdfWriter.getInstance(document, outputStream); document.open(); Image image; for (int i = 1; i <= pages; i++) { image = TiffImage.getTiffImage(rafa, i); image.scaleToFit(FIT_WIDTH, FIT_HEIGHT); document.add(image); } } catch (IOException e) { if (!e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) { logger.error("TIF转JPG异常,文件路径:" + strPdfFile, e); } throw new Exception(e); } finally { if (document != null) { document.close(); } if (rafa != null) { rafa.close(); } if (outputStream != null) { outputStream.close(); } } return strPdfFile; } }
List<String> listImageFiles = new ArrayList<>(); String baseUrl = BaseUrlFilter.getBaseUrl(); if (!new File(strInputFile).exists()) { logger.info("找不到文件【" + strInputFile + "】"); return null; } strOutputFile = strOutputFile.replaceAll(".jpg", ""); FileSeekableStream fileSeekStream = null; try { JPEGEncodeParam jpegEncodeParam = new JPEGEncodeParam(); TIFFEncodeParam tiffEncodeParam = new TIFFEncodeParam(); tiffEncodeParam.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4); tiffEncodeParam.setLittleEndian(false); fileSeekStream = new FileSeekableStream(strInputFile); ImageDecoder imageDecoder = ImageCodec.createImageDecoder("TIFF", fileSeekStream, null); int intTifCount = imageDecoder.getNumPages(); // logger.info("该tif文件共有【" + intTifCount + "】页"); // 处理目标文件夹,如果不存在则自动创建 File fileJpgPath = new File(strOutputFile); if (!fileJpgPath.exists() && !fileJpgPath.mkdirs()) { logger.error("{} 创建失败", strOutputFile); } // 循环,处理每页tif文件,转换为jpg for (int i = 0; i < intTifCount; i++) { String strJpg= strOutputFile + "/" + i + ".jpg"; File fileJpg = new File(strJpg); // 如果文件不存在,则生成 if (forceUpdatedCache|| !fileJpg.exists()) { RenderedImage renderedImage = imageDecoder.decodeAsRenderedImage(i); ParameterBlock pb = new ParameterBlock(); pb.addSource(renderedImage); pb.add(fileJpg.toString()); pb.add("JPEG"); pb.add(jpegEncodeParam); RenderedOp renderedOp = JAI.create("filestore", pb); renderedOp.dispose(); // logger.info("每页分别保存至: " + fileJpg.getCanonicalPath()); } strJpg = baseUrl+strJpg.replace(fileDir, ""); listImageFiles.add(strJpg); } } catch (IOException e) { if (!e.getMessage().contains("Bad endianness tag (not 0x4949 or 0x4d4d)") ) { logger.error("TIF转JPG异常,文件路径:" + strInputFile, e); } throw new Exception(e); } finally { if (fileSeekStream != null) { fileSeekStream.close(); } } return listImageFiles;
668
744
1,412
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/DownloadUtils.java
DownloadUtils
downLoad
class DownloadUtils { private final static Logger logger = LoggerFactory.getLogger(DownloadUtils.class); private static final String fileDir = ConfigConstants.getFileDir(); private static final String URL_PARAM_FTP_USERNAME = "ftp.username"; private static final String URL_PARAM_FTP_PASSWORD = "ftp.password"; private static final String URL_PARAM_FTP_CONTROL_ENCODING = "ftp.control.encoding"; private static final RestTemplate restTemplate = new RestTemplate(); private static final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); private static final ObjectMapper mapper = new ObjectMapper(); /** * @param fileAttribute fileAttribute * @param fileName 文件名 * @return 本地文件绝对路径 */ public static ReturnResponse<String> downLoad(FileAttribute fileAttribute, String fileName) {<FILL_FUNCTION_BODY>} /** * 获取真实文件绝对路径 * * @param fileName 文件名 * @return 文件路径 */ private static String getRelFilePath(String fileName, FileAttribute fileAttribute) { String type = fileAttribute.getSuffix(); if (null == fileName) { UUID uuid = UUID.randomUUID(); fileName = uuid + "." + type; } else { // 文件后缀不一致时,以type为准(针对simText【将类txt文件转为txt】) fileName = fileName.replace(fileName.substring(fileName.lastIndexOf(".") + 1), type); } String realPath = fileDir + fileName; File dirFile = new File(fileDir); if (!dirFile.exists() && !dirFile.mkdirs()) { logger.error("创建目录【{}】失败,可能是权限不够,请检查", fileDir); } return realPath; } }
// 忽略ssl证书 String urlStr = null; try { SslUtils.ignoreSsl(); urlStr = fileAttribute.getUrl().replaceAll("\\+", "%20").replaceAll(" ", "%20"); } catch (Exception e) { logger.error("忽略SSL证书异常:", e); } ReturnResponse<String> response = new ReturnResponse<>(0, "下载成功!!!", ""); String realPath = getRelFilePath(fileName, fileAttribute); // 判断是否非法地址 if (KkFileUtils.isIllegalFileName(realPath)) { response.setCode(1); response.setContent(null); response.setMsg("下载失败:文件名不合法!" + urlStr); return response; } if (!KkFileUtils.isAllowedUpload(realPath)) { response.setCode(1); response.setContent(null); response.setMsg("下载失败:不支持的类型!" + urlStr); return response; } if (fileAttribute.isCompressFile()) { //压缩包文件 直接赋予路径 不予下载 response.setContent(fileDir + fileName); response.setMsg(fileName); return response; } // 如果文件是否已经存在、且不强制更新,则直接返回文件路径 if (KkFileUtils.isExist(realPath) && !fileAttribute.forceUpdatedCache()) { response.setContent(realPath); response.setMsg(fileName); return response; } try { URL url = WebUtils.normalizedURL(urlStr); if (!fileAttribute.getSkipDownLoad()) { if (isHttpUrl(url)) { File realFile = new File(realPath); factory.setConnectionRequestTimeout(2000); //设置超时时间 factory.setConnectTimeout(10000); factory.setReadTimeout(72000); HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy()).build(); factory.setHttpClient(httpClient); //加入重定向方法 restTemplate.setRequestFactory(factory); RequestCallback requestCallback = request -> { request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL)); String proxyAuthorization = fileAttribute.getKkProxyAuthorization(); if(StringUtils.hasText(proxyAuthorization)){ Map<String,String> proxyAuthorizationMap = mapper.readValue(proxyAuthorization, Map.class); proxyAuthorizationMap.forEach((key, value) -> request.getHeaders().set(key, value)); } }; try { restTemplate.execute(url.toURI(), HttpMethod.GET, requestCallback, fileResponse -> { FileUtils.copyToFile(fileResponse.getBody(), realFile); return null; }); } catch (Exception e) { response.setCode(1); response.setContent(null); response.setMsg("下载失败:" + e); return response; } } else if (isFtpUrl(url)) { String ftpUsername = WebUtils.getUrlParameterReg(fileAttribute.getUrl(), URL_PARAM_FTP_USERNAME); String ftpPassword = WebUtils.getUrlParameterReg(fileAttribute.getUrl(), URL_PARAM_FTP_PASSWORD); String ftpControlEncoding = WebUtils.getUrlParameterReg(fileAttribute.getUrl(), URL_PARAM_FTP_CONTROL_ENCODING); FtpUtils.download(fileAttribute.getUrl(), realPath, ftpUsername, ftpPassword, ftpControlEncoding); } else { response.setCode(1); response.setMsg("url不能识别url" + urlStr); } } response.setContent(realPath); response.setMsg(fileName); return response; } catch (IOException | GalimatiasParseException e) { logger.error("文件下载失败,url:{}", urlStr); response.setCode(1); response.setContent(null); if (e instanceof FileNotFoundException) { response.setMsg("文件不存在!!!"); } else { response.setMsg(e.getMessage()); } return response; }
499
1,115
1,614
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/EncodingDetects.java
EncodingDetects
getJavaEncode
class EncodingDetects { private static final int DEFAULT_LENGTH = 4096; private static final int LIMIT = 50; private static final Logger logger = LoggerFactory.getLogger(EncodingDetects.class); public static String getJavaEncode(String filePath) { return getJavaEncode(new File(filePath)); } public static String getJavaEncode(File file) {<FILL_FUNCTION_BODY>} public static String getJavaEncode(byte[] content) { if (content != null && content.length <= LIMIT) { return SimpleEncodingDetects.getJavaEncode(content); } UniversalDetector detector = new UniversalDetector(null); detector.handleData(content, 0, content.length); detector.dataEnd(); String charsetName = detector.getDetectedCharset(); if (charsetName == null) { charsetName = Charset.defaultCharset().name(); } return charsetName; } }
int len = Math.min(DEFAULT_LENGTH, (int) file.length()); byte[] content = new byte[len]; try (InputStream fis = Files.newInputStream(file.toPath())) { fis.read(content, 0, len); } catch (IOException e) { logger.error("文件读取失败:{}", file.getPath()); } return getJavaEncode(content);
259
106
365
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/FtpUtils.java
FtpUtils
download
class FtpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class); public static FTPClient connect(String host, int port, String username, String password, String controlEncoding) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { ftpClient.login(username, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } ftpClient.setControlEncoding(controlEncoding); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return ftpClient; } public static void download(String ftpUrl, String localFilePath, String ftpUsername, String ftpPassword, String ftpControlEncoding) throws IOException {<FILL_FUNCTION_BODY>} }
String username = StringUtils.isEmpty(ftpUsername) ? ConfigConstants.getFtpUsername() : ftpUsername; String password = StringUtils.isEmpty(ftpPassword) ? ConfigConstants.getFtpPassword() : ftpPassword; String controlEncoding = StringUtils.isEmpty(ftpControlEncoding) ? ConfigConstants.getFtpControlEncoding() : ftpControlEncoding; URL url = new URL(ftpUrl); String host = url.getHost(); int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort(); String remoteFilePath = url.getPath(); LOGGER.debug("FTP connection url:{}, username:{}, password:{}, controlEncoding:{}, localFilePath:{}", ftpUrl, username, password, controlEncoding, localFilePath); FTPClient ftpClient = connect(host, port, username, password, controlEncoding); OutputStream outputStream = Files.newOutputStream(Paths.get(localFilePath)); ftpClient.enterLocalPassiveMode(); boolean downloadResult = ftpClient.retrieveFile(new String(remoteFilePath.getBytes(controlEncoding), StandardCharsets.ISO_8859_1), outputStream); LOGGER.debug("FTP download result {}", downloadResult); outputStream.flush(); outputStream.close(); ftpClient.logout(); ftpClient.disconnect();
263
350
613
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/KkFileUtils.java
KkFileUtils
deleteDirectory
class KkFileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(KkFileUtils.class); public static final String DEFAULT_FILE_ENCODING = "UTF-8"; private static final List<String> illegalFileStrList = new ArrayList<>(); static { illegalFileStrList.add("../"); illegalFileStrList.add("./"); illegalFileStrList.add("..\\"); illegalFileStrList.add(".\\"); illegalFileStrList.add("\\.."); illegalFileStrList.add("\\."); illegalFileStrList.add(".."); illegalFileStrList.add("..."); } /** * 检查文件名是否合规 * * @param fileName 文件名 * @return 合规结果, true:不合规,false:合规 */ public static boolean isIllegalFileName(String fileName) { for (String str : illegalFileStrList) { if (fileName.contains(str)) { return true; } } return false; } /** * 检查是否是数字 * * @param str 文件名 * @return 合规结果, true:不合规,false:合规 */ public static boolean isInteger(String str) { if (StringUtils.hasText(str)) { boolean strResult = str.matches("-?[0-9]+.?[0-9]*"); return strResult; } return false; } /** * 判断url是否是http资源 * * @param url url * @return 是否http */ public static boolean isHttpUrl(URL url) { return url.getProtocol().toLowerCase().startsWith("file") || url.getProtocol().toLowerCase().startsWith("http"); } /** * 判断url是否是ftp资源 * * @param url url * @return 是否ftp */ public static boolean isFtpUrl(URL url) { return "ftp".equalsIgnoreCase(url.getProtocol()); } /** * 删除单个文件 * * @param fileName 要删除的文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFileByName(String fileName) { File file = new File(fileName); // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 if (file.exists() && file.isFile()) { if (file.delete()) { LOGGER.info("删除单个文件" + fileName + "成功!"); return true; } else { LOGGER.info("删除单个文件" + fileName + "失败!"); return false; } } else { LOGGER.info("删除单个文件失败:" + fileName + "不存在!"); return false; } } public static String htmlEscape(String input) { if (StringUtils.hasText(input)) { //input = input.replaceAll("\\{", "%7B").replaceAll("}", "%7D").replaceAll("\\\\", "%5C"); String htmlStr = HtmlUtils.htmlEscape(input, "UTF-8"); //& -> &amp; return htmlStr.replace("&amp;", "&"); } return input; } /** * 通过文件名获取文件后缀 * * @param fileName 文件名称 * @return 文件后缀 */ public static String suffixFromFileName(String fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); } /** * 根据文件路径删除文件 * * @param filePath 绝对路径 */ public static void deleteFileByPath(String filePath) { File file = new File(filePath); if (file.exists() && !file.delete()) { LOGGER.warn("压缩包源文件删除失败:{}!", filePath); } } /** * 删除目录及目录下的文件 * * @param dir 要删除的目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String dir) {<FILL_FUNCTION_BODY>} /** * 判断文件是否允许上传 * * @param file 文件扩展名 * @return 是否允许上传 */ public static boolean isAllowedUpload(String file) { String fileType = suffixFromFileName(file); for (String type : ConfigConstants.getProhibit()) { if (type.equals(fileType)){ return false; } } return !ObjectUtils.isEmpty(fileType); } /** * 判断文件是否存在 * * @param filePath 文件路径 * @return 是否存在 true:存在,false:不存在 */ public static boolean isExist(String filePath) { File file = new File(filePath); return file.exists(); } }
// 如果dir不以文件分隔符结尾,自动添加文件分隔符 if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); // 如果dir对应的文件不存在,或者不是一个目录,则退出 if ((!dirFile.exists()) || (!dirFile.isDirectory())) { LOGGER.info("删除目录失败:" + dir + "不存在!"); return false; } boolean flag = true; // 删除文件夹中的所有文件包括子目录 File[] files = dirFile.listFiles(); for (int i = 0; i < Objects.requireNonNull(files).length; i++) { // 删除子文件 if (files[i].isFile()) { flag = KkFileUtils.deleteFileByName(files[i].getAbsolutePath()); if (!flag) { break; } } else if (files[i].isDirectory()) { // 删除子目录 flag = KkFileUtils.deleteDirectory(files[i].getAbsolutePath()); if (!flag) { break; } } } if (!dirFile.delete() || !flag) { LOGGER.info("删除目录失败!"); return false; } return true;
1,373
359
1,732
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/LocalOfficeUtils.java
LocalOfficeUtils
getDefaultOfficeHome
class LocalOfficeUtils { public static final String OFFICE_HOME_KEY = "office.home"; public static final String DEFAULT_OFFICE_HOME_VALUE = "default"; private static final String EXECUTABLE_DEFAULT = "program/soffice.bin"; private static final String EXECUTABLE_MAC = "program/soffice"; private static final String EXECUTABLE_MAC_41 = "MacOS/soffice"; private static final String EXECUTABLE_WINDOWS = "program/soffice.exe"; public static File getDefaultOfficeHome() {<FILL_FUNCTION_BODY>} private static File findOfficeHome(final String executablePath, final String... homePaths) { return Stream.of(homePaths) .filter(homePath -> Files.isRegularFile(Paths.get(homePath, executablePath))) .findFirst() .map(File::new) .orElse(null); } }
Properties properties = new Properties(); String customizedConfigPath = ConfigUtils.getCustomizedConfigPath(); try { BufferedReader bufferedReader = new BufferedReader(new FileReader(customizedConfigPath)); properties.load(bufferedReader); ConfigUtils.restorePropertiesFromEnvFormat(properties); } catch (Exception ignored) {} String officeHome = properties.getProperty(OFFICE_HOME_KEY); if (officeHome != null && !DEFAULT_OFFICE_HOME_VALUE.equals(officeHome)) { return new File(officeHome); } if (OSUtils.IS_OS_WINDOWS) { String userDir = ConfigUtils.getUserDir(); // Try to find the most recent version of LibreOffice or OpenOffice, // starting with the 64-bit version. %ProgramFiles(x86)% on 64-bit // machines; %ProgramFiles% on 32-bit ones final String programFiles64 = System.getenv("ProgramFiles"); final String programFiles32 = System.getenv("ProgramFiles(x86)"); return findOfficeHome(EXECUTABLE_WINDOWS, userDir + File.separator + "LibreOfficePortable" + File.separator + "App" + File.separator + "libreoffice", programFiles32 + File.separator + "LibreOffice", programFiles64 + File.separator + "LibreOffice 7", programFiles32 + File.separator + "LibreOffice 7", programFiles64 + File.separator + "LibreOffice 6", programFiles32 + File.separator + "LibreOffice 6", programFiles64 + File.separator + "LibreOffice 5", programFiles32 + File.separator + "LibreOffice 5", programFiles64 + File.separator + "LibreOffice 4", programFiles32 + File.separator + "LibreOffice 4", programFiles32 + File.separator + "OpenOffice 4", programFiles64 + File.separator + "LibreOffice 3", programFiles32 + File.separator + "LibreOffice 3", programFiles32 + File.separator + "OpenOffice.org 3"); } else if (OSUtils.IS_OS_MAC) { File homeDir = findOfficeHome(EXECUTABLE_MAC_41, "/Applications/LibreOffice.app/Contents", "/Applications/OpenOffice.app/Contents", "/Applications/OpenOffice.org.app/Contents"); if (homeDir == null) { homeDir = findOfficeHome(EXECUTABLE_MAC, "/Applications/LibreOffice.app/Contents", "/Applications/OpenOffice.app/Contents", "/Applications/OpenOffice.org.app/Contents"); } return homeDir; } else { // Linux or other *nix variants return findOfficeHome(EXECUTABLE_DEFAULT, "/opt/libreoffice6.0", "/opt/libreoffice6.1", "/opt/libreoffice6.2", "/opt/libreoffice6.3", "/opt/libreoffice6.4", "/opt/libreoffice7.0", "/opt/libreoffice7.1", "/opt/libreoffice7.2", "/opt/libreoffice7.3", "/opt/libreoffice7.4", "/opt/libreoffice7.5", "/opt/libreoffice7.6", "/usr/lib64/libreoffice", "/usr/lib/libreoffice", "/usr/local/lib64/libreoffice", "/usr/local/lib/libreoffice", "/opt/libreoffice", "/usr/lib64/openoffice", "/usr/lib64/openoffice.org3", "/usr/lib64/openoffice.org", "/usr/lib/openoffice", "/usr/lib/openoffice.org3", "/usr/lib/openoffice.org", "/opt/openoffice4", "/opt/openoffice.org3"); }
249
1,062
1,311
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/OfficeUtils.java
OfficeUtils
isCompatible
class OfficeUtils { private static final String POI_INVALID_PASSWORD_MSG = "password"; /** * 判断office(word,excel,ppt)文件是否受密码保护 * * @param path office文件路径 * @return 是否受密码保护 */ public static boolean isPwdProtected(String path) { InputStream propStream = null; try { propStream = Files.newInputStream(Paths.get(path)); ExtractorFactory.createExtractor(propStream); } catch (IOException | EncryptedDocumentException e) { if (e.getMessage().toLowerCase().contains(POI_INVALID_PASSWORD_MSG)) { return true; } } catch (Exception e) { Throwable[] throwableArray = ExceptionUtils.getThrowables(e); for (Throwable throwable : throwableArray) { if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) { if (e.getMessage().toLowerCase().contains(POI_INVALID_PASSWORD_MSG)) { return true; } } } }finally { if(propStream!=null) {//如果文件输入流不是null try { propStream.close();//关闭文件输入流 } catch (IOException e) { e.printStackTrace(); } } } return false; } /** * 判断office文件是否可打开(兼容) * * @param path office文件路径 * @param password 文件密码 * @return 是否可打开(兼容) */ public static synchronized boolean isCompatible(String path, String password) {<FILL_FUNCTION_BODY>} }
InputStream propStream = null; try { propStream = Files.newInputStream(Paths.get(path)); Biff8EncryptionKey.setCurrentUserPassword(password); ExtractorFactory.createExtractor(propStream); } catch (Exception e) { return false; } finally { Biff8EncryptionKey.setCurrentUserPassword(null); if(propStream!=null) {//如果文件输入流不是null try { propStream.close();//关闭文件输入流 } catch (IOException e) { e.printStackTrace(); } } } return true;
459
163
622
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/RarUtils.java
RarUtils
getUTF8BytesFromGBKString
class RarUtils { private static final String fileDir = ConfigConstants.getFileDir(); public static byte[] getUTF8BytesFromGBKString(String gbkStr) {<FILL_FUNCTION_BODY>} public static String getUtf8String(String str) { if (str != null && str.length() > 0) { String needEncodeCode = "ISO-8859-1"; String neeEncodeCode = "ISO-8859-2"; String gbkEncodeCode = "GBK"; try { if (Charset.forName(needEncodeCode).newEncoder().canEncode(str)) { str = new String(str.getBytes(needEncodeCode), StandardCharsets.UTF_8); } if (Charset.forName(neeEncodeCode).newEncoder().canEncode(str)) { str = new String(str.getBytes(neeEncodeCode), StandardCharsets.UTF_8); } if (Charset.forName(gbkEncodeCode).newEncoder().canEncode(str)) { str = new String(getUTF8BytesFromGBKString(str), StandardCharsets.UTF_8); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return str; } /** * 判断是否是中日韩文字 */ private static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS; } public static boolean judge(char c){ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'); } public static String specialSymbols(String str) { //去除压缩包文件字符串中特殊符号 Pattern p = Pattern.compile("\\s|\t|\r|\n|\\+|#|&|=|\\p{P}"); // Pattern p = Pattern.compile("\\s|\\+|#|&|=|\\p{P}"); Matcher m = p.matcher(str); return m.replaceAll(""); } public static boolean isMessyCode(String strName) { //去除字符串中的空格 制表符 换行 回车 strName = specialSymbols(strName); //处理之后转换成字符数组 char[] ch = strName.trim().toCharArray(); for (char c : ch) { //判断是否是数字或者英文字符 if (!judge(c)) { //判断是否是中日韩文 if (!isChinese(c)) { //如果不是数字或者英文字符也不是中日韩文则表示是乱码返回true return true; } } } //表示不是乱码 返回false return false; } /** * 读取文件目录树 */ public static List<ZtreeNodeVo> getTree(String rootPath) { List<ZtreeNodeVo> nodes = new ArrayList<>(); File file = new File(fileDir+rootPath); ZtreeNodeVo node = traverse(file); nodes.add(node); return nodes; } private static ZtreeNodeVo traverse(File file) { ZtreeNodeVo pathNodeVo = new ZtreeNodeVo(); pathNodeVo.setId(file.getAbsolutePath().replace(fileDir, "").replace("\\", "/")); pathNodeVo.setName(file.getName()); pathNodeVo.setPid(file.getParent().replace(fileDir, "").replace("\\", "/")); if (file.isDirectory()) { List<ZtreeNodeVo> subNodeVos = new ArrayList<>(); File[] subFiles = file.listFiles(); if (subFiles == null) { return pathNodeVo; } for (File subFile : subFiles) { ZtreeNodeVo subNodeVo = traverse(subFile); subNodeVos.add(subNodeVo); } pathNodeVo.setChildren(subNodeVos); } return pathNodeVo; } }
int n = gbkStr.length(); byte[] utfBytes = new byte[3 * n]; int k = 0; for (int i = 0; i < n; i++) { int m = gbkStr.charAt(i); if (m < 128 && m >= 0) { utfBytes[k++] = (byte) m; continue; } utfBytes[k++] = (byte) (0xe0 | (m >> 12)); utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f)); utfBytes[k++] = (byte) (0x80 | (m & 0x3f)); } if (k < utfBytes.length) { byte[] tmp = new byte[k]; System.arraycopy(utfBytes, 0, tmp, 0, k); return tmp; } return utfBytes;
1,345
266
1,611
<no_super_class>
kekingcn_kkFileView
kkFileView/server/src/main/java/cn/keking/utils/SslUtils.java
miTM
ignoreSsl
class miTM implements TrustManager, X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } } /** * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用 */ public static void ignoreSsl() throws Exception {<FILL_FUNCTION_BODY>
HostnameVerifier hv = (urlHostName, session) -> true; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv);
160
51
211
<no_super_class>