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 ManualTrig... |
return Collections.singletonList(
Variable
.of("_now",
LocaleUtils.resolveMessage(
"message.scene_term_column_now",
"服务器时间"))
.withType(DateTimeType.ID)
.withTermType(TermTypes.lookup... | 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 n... |
return Collections.singletonList(
Variable
.of("_now",
LocaleUtils.resolveMessage(
"message.scene_term_column_now",
"服务器时间"))
.withType(DateTimeType.ID)
.withTermType(TermTypes.lookup... | 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 d... |
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) {
... | 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(... |
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;
p... |
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)... | 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;
/**
* 处理告警
*
... |
return this
.queryPager(query)
.flatMap(result -> Flux
.fromIterable(result.getData())
.index()
.flatMap(tp2 -> this
// 转换为详情
.convertDetail(tp2.getT2())
.map(detail -> Tuples.of(... | 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 Exceptio... |
return findById(DEFAULT_ALARM_ID)
.switchIfEmpty(
Mono.fromCallable(() -> {
ClassPathResource resource = new ClassPathResource("alarm-level.json");
try (InputStream stream = resource.getInputStream()) {
String json = St... | 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>> queryP... |
indexManager.putIndex(
new DefaultElasticSearchIndexMetadata(ALARM_HISTORY_INDEX)
.addProperty("id", StringType.GLOBAL)
.addProperty("alarmConfigId", StringType.GLOBAL)
.addProperty("alarmConfigName", StringType.GLOBAL)
.addProperty("a... | 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 Mon... |
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"... |
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)
... | 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,
... |
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 =", columnFul... | 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,
... |
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 =", columnFu... | 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")
@Dele... |
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
... | 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_FUNCTIO... |
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>>) ,publi... |
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.pu... | 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();
}
... |
//解决请求参数最大长度问题
return factory -> factory
.addServerCustomizers(
httpServer ->
httpServer.httpRequestDecoder(spec -> {
spec.maxInitialLineLength(
Math.max(spec.maxInitialLineLength(),
... | 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 ... |
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... |
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<jav... |
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();
}
/** Ret... |
// 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 IllegalArgumen... | 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",
"lastA... |
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();
... | 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<jav... |
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 = c... |
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() {
r... |
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", userProv... | 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<jav... |
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)... |
// 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 bein... |
// 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.inc... | 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> 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 cr... | 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 i... |
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);
Strin... | 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 i... |
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[... | 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 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... |
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 FileSys... |
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 Iter... |
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 ... |
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 pat... | 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 fileSyste... |
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;
... | 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(b... |
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... |
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[], in... |
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();
}
... |
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 = n... |
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 = ... |
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' + 'APPEN... | 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... |
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<jav... |
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-sy... |
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... | 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-s... |
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()... | 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\'";
... |
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<?>[]) ... |
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... |
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)));
... | 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.AbstractWatch... |
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 = createGroup... |
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());
... | 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<jav... |
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()... |
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();
}
... | 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");
priva... |
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_EXE... | 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<jav... |
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);
S... |
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.ParseResu... |
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(l... |
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<jav... |
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);
}
... |
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 g... |
// 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,... | 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... |
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... |
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\\b... | 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.ParseResu... |
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 prometheus... |
Info info =
Info.builder()
.name("jmx_exporter_build_info")
.help("JMX Exporter build information")
.labelNames("name", "version")
.register(prometheusRegistry);
Package pkg = this.getClass(... | 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<>();
... |
try {
FileReader fr = new FileReader(configFile);
try {
Map<String, Object> newYamlConfig = new Yaml().load(fr);
config = loadConfig(newYamlConfig);
config.lastUpdate = configFile.lastModified();
configReloadSuccess.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
"="... |
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... |
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()) {
... | 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";
... |
if (autoExcludeObjectNameAttributes) {
Set<String> attribteNameSet =
excludeObjectNameAttributesMap.computeIfAbsent(
objectName, o -> Collections.synchronizedSet(new HashSet<>()));
LOGGER.log(
Level.FINE,
... | 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"));... |
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))
.print... | 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);
... |
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.not... |
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);
... |
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 suppl... |
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 = passw... |
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... |
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;
}
/... | 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... |
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 St... |
if (username == null || password == null) {
return false;
}
Credentials credentials = new Credentials(username, password);
if (validCredentialsCache.contains(credentials)) {
return true;
} else if (invalidCredentialsCache.contains(credentials)) {
... | 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 getRe... |
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 al... |
try {
PBEKeySpec pbeKeySpec =
new PBEKeySpec(
password.toCharArray(),
salt.getBytes(StandardCharsets.UTF_8),
iterations,
keyLength * 8);
SecretKeyFactory s... | 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 getRe... |
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 k... |
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... | 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 no... |
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;
}
... |
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) {
thr... | 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 = I... | 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 f... |
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> ");
... | 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.getB... | 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;
... |
Config config = new Config();
config.useSingleServer().setAddress(address)
.setConnectionMinimumIdleSize(connectionMinimumIdleSize)
.setConnectionPoolSize(connectionPoolSize)
.setDatabase(database)
.setDnsMonitoring(dnsMonitoring)
... | 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.i... |
Set<String> filterUri = new HashSet<>();
BaseUrlFilter filter = new BaseUrlFilter();
FilterRegistrationBean<BaseUrlFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setUrlPatterns(filterUri);
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 ... |
List<String> imgUrls = new ArrayList<>();
String baseUrl = BaseUrlFilter.getBaseUrl();
String packagePath = "_"; //防止文件名重复 压缩包统一生成文件添加_符号
String folderName = filePath.replace(fileDir, ""); //修复压缩包 多重目录获取路径错误
if (fileAttribute.isCompressFile()) { //压缩包文件 直接赋予路径 不予下载
f... | 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(Fi... |
while (true) {
String url = null;
try {
url = cacheService.takeQueueTask();
if (url != null) {
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(url, null);
FileType fileT... | 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 time... |
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 b... | 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);
... |
File outputFile = new File(outputFilePath_end);
// 假如目标路径不存在,则新建该路径
if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
logger.error("创建目录【{}】失败,请检查目录权限!",outputFilePath_end);
}
LocalConverter.Builder builder;
Map<String, Objec... | 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;
pu... |
// 预览Type,参数传了就取参数的,没传取系统默认
String officePreviewType = fileAttribute.getOfficePreviewType() == null ? ConfigConstants.getOfficePreviewType() : fileAttribute.getOfficePreviewType();
String baseUrl = BaseUrlFilter.getBaseUrl();
boolean forceUpdatedCache = fileAttribute.forceUpdatedCache()... | 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 = fileHandlerS... |
// 不是http开头,浏览器不能直接访问,需下载到本地
if (url != null && !url.toLowerCase().startsWith("http")) {
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, null);
if (response.isFailure()) {
return otherFilePreview.notSupportedFile(model, fileAttribute, resp... | 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 CompressFilePreview... |
String fileName=fileAttribute.getName();
String filePassword = fileAttribute.getFilePassword();
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache();
String fileTree = null;
// 判断文件名是否存在(redis缓存读取)
if (forceUpdatedCache || !StringUtils.hasText(fileHandlerService.g... | 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 otherFilePrevie... |
FFmpegFrameGrabber frameGrabber = FFmpegFrameGrabber.createDefault(filePath);
Frame captured_frame;
FFmpegFrameRecorder recorder = null;
try {
File desFile = new File(outFilePath);
//判断一下防止重复转换
if (desFile.exists()) {
return outFilePat... | 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 fileHandlerServic... |
// 预览Type,参数传了就取参数的,没传取系统默认
String officePreviewType = fileAttribute.getOfficePreviewType();
boolean userToken = fileAttribute.getUsePasswordCache();
String baseUrl = BaseUrlFilter.getBaseUrl();
String suffix = fileAttribute.getSuffix(); //获取文件后缀
String fileName = fileA... | 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 ot... |
String pdfName = fileAttribute.getName(); //获取原始文件名
String officePreviewType = fileAttribute.getOfficePreviewType(); //转换类型
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
String outFilePath = fileAttribute.getOutFilePath(); //生成的文件路径
String originFi... | 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 = fil... |
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))... | 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-... |
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 = fil... |
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".equ... | 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 = fileHandle... |
String fileName = fileAttribute.getName();
String tifPreviewType = ConfigConstants.getTifPreviewType();
String cacheName = fileAttribute.getCacheName();
String outFilePath = fileAttribute.getOutFilePath();
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache();
if ... | 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;// 定义图片上显示验... |
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... | 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.get... |
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.s... | 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。
*
* @p... |
List<String> listImageFiles = new ArrayList<>();
String baseUrl = BaseUrlFilter.getBaseUrl();
if (!new File(strInputFile).exists()) {
logger.info("找不到文件【" + strInputFile + "】");
return null;
}
strOutputFile = strOutputFile.replaceAll(".jpg", "");
... | 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.pas... |
// 忽略ssl证书
String urlStr = null;
try {
SslUtils.ignoreSsl();
urlStr = fileAttribute.getUrl().replaceAll("\\+", "%20").replaceAll(" ", "%20");
} catch (Exception e) {
logger.error("忽略SSL证书异常:", e);
}
ReturnResponse<String> response = ne... | 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));
}... |
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());
}
... | 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, po... |
String username = StringUtils.isEmpty(ftpUsername) ? ConfigConstants.getFtpUsername() : ftpUsername;
String password = StringUtils.isEmpty(ftpPassword) ? ConfigConstants.getFtpPassword() : ftpPassword;
String controlEncoding = StringUtils.isEmpty(ftpControlEncoding) ? ConfigConstants.getFtpCont... | 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("../");
illegalFi... |
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator)) {
dir = dir + File.separator;
}
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
LOGGER.info("删除目录失败:" + dir + "不存在!")... | 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 sta... |
Properties properties = new Properties();
String customizedConfigPath = ConfigUtils.getCustomizedConfigPath();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(customizedConfigPath));
properties.load(bufferedReader);
ConfigUtils.restore... | 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 {
... |
InputStream propStream = null;
try {
propStream = Files.newInputStream(Paths.get(path));
Biff8EncryptionKey.setCurrentUserPassword(password);
ExtractorFactory.createExtractor(propStream);
} catch (Exception e) {
return false;
} finally {
... | 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... |
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;
}
utfByte... | 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(X509Certific... |
HostnameVerifier hv = (urlHostName, session) -> true;
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
| 160 | 51 | 211 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.