Skip to content

Commit

Permalink
first spike towards #817 - added the missing hawtio-util ;)
Browse files Browse the repository at this point in the history
  • Loading branch information
jstrachan committed Dec 5, 2013
1 parent 42fdb6e commit ab975a7
Show file tree
Hide file tree
Showing 13 changed files with 920 additions and 0 deletions.
39 changes: 39 additions & 0 deletions hawtio-util/pom.xml
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>io.hawt</groupId>
<artifactId>project</artifactId>
<version>1.3-SNAPSHOT</version>
</parent>

<modelVersion>4.0.0</modelVersion>
<artifactId>hawtio-util</artifactId>
<name>${project.artifactId}</name>
<description>hawtio :: hawtio-util</description>

<properties>
</properties>

<dependencies>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>

<!-- testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
118 changes: 118 additions & 0 deletions hawtio-util/src/main/java/io/hawt/util/FileFilters.java
@@ -0,0 +1,118 @@
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hawt.util;

import java.io.File;
import java.io.FileFilter;

/**
* A number of helper functions for creating {@link FileFilter} objects on a {@link File} object.
*/
public class FileFilters {
private static final FileFilter TRUE_FILTER = new FileFilter() {
@Override
public String toString() {
return "TrueFileFilter";
}

@Override
public boolean accept(File pathname) {
return true;
}
};

public static FileFilter createFileFilter(String wildcard) {
if (Strings.isNotBlank(wildcard)) {
int idx = wildcard.indexOf('*');
if (idx < 0) {
return nameEqualsFilter(wildcard);
}
int lastIdx = wildcard.lastIndexOf(idx);
if (lastIdx < 0) {
lastIdx = idx;
}
FileFilter endsWith = nameEndsWithFilter(wildcard.substring(lastIdx + 1));
if (idx <= 0) {
return endsWith;
} else {
return andFilter(nameStartsWithFilter(wildcard.substring(0, idx)), endsWith);
}
}
return trueFilter();
}

public static FileFilter nameEqualsFilter(final String name) {
return new FileFilter() {
@Override
public String toString() {
return "FileNameEqualsFilter(" + name + ")";
}

@Override
public boolean accept(File file) {
return name.equals(file.getName());
}
};
}

public static FileFilter nameStartsWithFilter(final String name) {
return new FileFilter() {
@Override
public String toString() {
return "FileNameStartsWithFilter(" + name + ")";
}

@Override
public boolean accept(File file) {
return file.getName().startsWith(name);
}
};
}

public static FileFilter nameEndsWithFilter(final String name) {
return new FileFilter() {
@Override
public String toString() {
return "FileNameEndsWithFilter(" + name + ")";
}

@Override
public boolean accept(File file) {
return file.getName().endsWith(name);
}
};
}

public static FileFilter andFilter(final FileFilter filter1, final FileFilter filter2) {
return new FileFilter() {
@Override
public String toString() {
return "AndFilter(" + filter1 + " && " + filter2 + ")";
}

@Override
public boolean accept(File file) {
return filter1.accept(file) && filter2.accept(file);
}
};
}

public static FileFilter trueFilter() {
return TRUE_FILTER;
}
}
62 changes: 62 additions & 0 deletions hawtio-util/src/main/java/io/hawt/util/FileLocker.java
@@ -0,0 +1,62 @@
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hawt.util;

import java.io.File;
import java.io.IOException;

/**
* A simple API to a file lock
*/
public class FileLocker {
private final File lockFile;

/**
* Attempts to grab the lock for the given file, returning a FileLock if
* the lock has been created; otherwise it returns null
*/
public static FileLocker getLock(File lockFile) {
lockFile.getParentFile().mkdirs();
if (!lockFile.exists()) {
try {
IOHelper.write(lockFile, "I have the lock!");
lockFile.deleteOnExit();
return new FileLocker(lockFile);
} catch (IOException e) {
// Ignore
}
}
return null;

}

public FileLocker(File lockFile) {
this.lockFile = lockFile;
}

@Override
public String toString() {
return "FileLock(" + lockFile + ")";
}

public void destroy() {
if (lockFile.exists()) {
lockFile.delete();
}
}
}
43 changes: 43 additions & 0 deletions hawtio-util/src/main/java/io/hawt/util/Files.java
@@ -0,0 +1,43 @@
/**
* Copyright (C) 2013 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hawt.util;

import java.io.File;

/**
*/
public class Files {
/**
* Recursively deletes the given file whether its a file or directory returning the number
* of files deleted
*/
public static int recursiveDelete(File file) {
int answer = 0;
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
answer += recursiveDelete(child);
}
}
}
if (file.delete()) {
answer += 1;
}
return answer;
}}
113 changes: 113 additions & 0 deletions hawtio-util/src/main/java/io/hawt/util/IOHelper.java
@@ -0,0 +1,113 @@
package io.hawt.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
* A collection of IO helpers
*/
public class IOHelper {
public static final int BUFFER_SIZE = 64 * 1024;

private static final transient Logger LOG = LoggerFactory.getLogger(IOHelper.class);

public static String readFully(File file) throws IOException {
return readFully(new BufferedReader(new FileReader(file)));
}

/**
* Reads the entire reader into memory as a String
*/
public static String readFully(BufferedReader reader) throws IOException {
if (reader == null) {
return null;
}

StringBuilder sb = new StringBuilder(BUFFER_SIZE);
char[] buf = new char[BUFFER_SIZE];
try {
int len;
// read until we reach then end which is the -1 marker
while ((len = reader.read(buf)) != -1) {
sb.append(buf, 0, len);
}
} finally {
IOHelper.close(reader, "reader", LOG);
}

return sb.toString();
}

/**
* Closes the given resource if it is available, logging any closing exceptions to the given log.
*
* @param closeable the object to close
* @param name the name of the resource
* @param log the log to use when reporting closure warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
*/
public static void close(Closeable closeable, String name, Logger log) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot close: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot close. Reason: " + e.getMessage(), e);
}
}
}
}


/**
* Writes the text to the given file, overwriting the previous file if it existed.
*/
public static void write(File file, String text) throws IOException {
write(file, text, false);
}

/**
* Writes the given text to the file; either in append mode or replace mode depending
* the append flag
*/
public static void write(File file, String text, boolean append) throws IOException {
FileWriter writer = new FileWriter(file, append);
try {
writer.write(text);
} finally {
writer.close();
}
}

public static int copy(final Reader input, final Writer output) throws IOException {
return copy(input, output, BUFFER_SIZE);
}

public static int copy(final Reader input, final Writer output, int bufferSize) throws IOException {
final char[] buffer = new char[bufferSize];
int n = input.read(buffer);
int total = 0;
while (-1 != n) {
output.write(buffer, 0, n);
total += n;
n = input.read(buffer);
}
output.flush();
return total;
}

}

0 comments on commit ab975a7

Please sign in to comment.