repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // }
import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects;
private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } } private InvalidOptionConfigurationException createInvalidOptionSpecificationException(String description) { return new InvalidOptionConfigurationException(getOptionId() + ' ' + description); } private InvalidCommandLineException createInvalidCommandLineException(String description) { return new InvalidCommandLineException(getOptionId() + ' ' + description); } private RuntimeException createInternalErrorException(String description) {
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } } private InvalidOptionConfigurationException createInvalidOptionSpecificationException(String description) { return new InvalidOptionConfigurationException(getOptionId() + ' ' + description); } private InvalidCommandLineException createInvalidCommandLineException(String description) { return new InvalidCommandLineException(getOptionId() + ' ' + description); } private RuntimeException createInternalErrorException(String description) {
return new InternalErrorException(getOptionId() + ' ' + description);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/happy/BasicParserTest.java
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // }
import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static org.assertj.core.api.Assertions.assertThat;
package com.github.jankroken.commandline.happy; public class BasicParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-f", "hello.txt", "-v"};
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // Path: src/test/java/com/github/jankroken/commandline/happy/BasicParserTest.java import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static org.assertj.core.api.Assertions.assertThat; package com.github.jankroken.commandline.happy; public class BasicParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-f", "hello.txt", "-v"};
final var config = parse(SimpleConfiguration.class, args, SIMPLE);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/util/ArrayIteratorTest.java
// Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.*;
package com.github.jankroken.commandline.util; public class ArrayIteratorTest { @Test public void testEmpty() {
// Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/util/ArrayIteratorTest.java import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.*; package com.github.jankroken.commandline.util; public class ArrayIteratorTest { @Test public void testEmpty() {
var ai = new ArrayIterator<>(EMPTY_STRING_ARRAY);
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecificationFactory.java
// Path: src/main/java/com/github/jankroken/commandline/util/Methods.java // public class Methods { // // private final Class<?> annotatedClass; // // public Methods(Class<?> annotatedClass) { // this.annotatedClass = annotatedClass; // } // // public List<Method> byAnnotation(Class<? extends Annotation> searchAnnotation) { // List<Method> methods = new ArrayList<>(); // methodLoop: // for (final var method : annotatedClass.getMethods()) { // if (method.isAnnotationPresent(searchAnnotation)) { // methods.add(method); // continue methodLoop; // } // } // return methods; // } // }
import com.github.jankroken.commandline.annotations.*; import com.github.jankroken.commandline.util.Methods; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
} else if (annotation instanceof LongSwitch) { builder.addLongSwitch(((LongSwitch) annotation).value()); } else if (annotation instanceof ShortSwitch) { builder.addShortSwitch(((ShortSwitch) annotation).value()); } else if (annotation instanceof Toggle) { builder.addToggle(((Toggle) annotation).value()); } else if (annotation instanceof SingleArgument) { builder.addSingleArgument(); } else if (annotation instanceof AllAvailableArguments) { builder.addAllAvailableArguments(); } else if (annotation instanceof ArgumentsUntilDelimiter) { builder.addUntilDelimiter(((ArgumentsUntilDelimiter) annotation).value()); } else if (annotation instanceof SubConfiguration) { builder.addSubset(((SubConfiguration) annotation).value()); } else if (annotation instanceof Required) { builder.addRequired(); } else if (annotation instanceof Multiple) { builder.addOccurrences(Occurrences.MULTIPLE); } else if (annotation instanceof LooseArguments) { builder.addLooseArgs(); } else { // todo System.out.println("Unhandled annotation: " + annotation); } } return builder.getOptionSpecification(); } public static List<OptionSpecification> getOptionSpecifications(Object spec, Class<?> optionClass) {
// Path: src/main/java/com/github/jankroken/commandline/util/Methods.java // public class Methods { // // private final Class<?> annotatedClass; // // public Methods(Class<?> annotatedClass) { // this.annotatedClass = annotatedClass; // } // // public List<Method> byAnnotation(Class<? extends Annotation> searchAnnotation) { // List<Method> methods = new ArrayList<>(); // methodLoop: // for (final var method : annotatedClass.getMethods()) { // if (method.isAnnotationPresent(searchAnnotation)) { // methods.add(method); // continue methodLoop; // } // } // return methods; // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecificationFactory.java import com.github.jankroken.commandline.annotations.*; import com.github.jankroken.commandline.util.Methods; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; } else if (annotation instanceof LongSwitch) { builder.addLongSwitch(((LongSwitch) annotation).value()); } else if (annotation instanceof ShortSwitch) { builder.addShortSwitch(((ShortSwitch) annotation).value()); } else if (annotation instanceof Toggle) { builder.addToggle(((Toggle) annotation).value()); } else if (annotation instanceof SingleArgument) { builder.addSingleArgument(); } else if (annotation instanceof AllAvailableArguments) { builder.addAllAvailableArguments(); } else if (annotation instanceof ArgumentsUntilDelimiter) { builder.addUntilDelimiter(((ArgumentsUntilDelimiter) annotation).value()); } else if (annotation instanceof SubConfiguration) { builder.addSubset(((SubConfiguration) annotation).value()); } else if (annotation instanceof Required) { builder.addRequired(); } else if (annotation instanceof Multiple) { builder.addOccurrences(Occurrences.MULTIPLE); } else if (annotation instanceof LooseArguments) { builder.addLooseArgs(); } else { // todo System.out.println("Unhandled annotation: " + annotation); } } return builder.getOptionSpecification(); } public static List<OptionSpecification> getOptionSpecifications(Object spec, Class<?> optionClass) {
var methods = new Methods(optionClass).byAnnotation(Option.class);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/happy/SimpleParserTest.java
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // }
import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static org.assertj.core.api.Assertions.assertThat;
package com.github.jankroken.commandline.happy; public class SimpleParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-f", "hello.txt", "-v"};
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // Path: src/test/java/com/github/jankroken/commandline/happy/SimpleParserTest.java import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static org.assertj.core.api.Assertions.assertThat; package com.github.jankroken.commandline.happy; public class SimpleParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-f", "hello.txt", "-v"};
final var config = parse(SimpleConfiguration.class, args, SIMPLE);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/domain/LongOrCompactTokenizerTest.java
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java // public class LongOrCompactTokenizer implements Tokenizer { // // private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); // private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); // private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); // private final PeekIterator<String> stringIterator; // private boolean argumentEscapeEncountered; // private String argumentTerminator; // private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); // // public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { // this.stringIterator = stringIterator; // } // // public void setArgumentTerminator(String argumentTerminator) { // this.argumentTerminator = argumentTerminator; // } // // public boolean hasNext() { // return stringIterator.hasNext(); // } // // // this is a mess - need to be cleaned up // public Token peek() { // if (!splitTokens.isEmpty()) { // return splitTokens.peek(); // } // final var value = stringIterator.peek(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return peek(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // var tokens = splitSwitchTokens(value); // return tokens.get(0); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // // this is a mess - needs to be cleaned up // public Token next() { // if (!splitTokens.isEmpty()) { // return splitTokens.remove(); // } // var value = stringIterator.next(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // argumentTerminator = null; // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return next(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // splitTokens.addAll(splitSwitchTokens(value)); // return splitTokens.remove(); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // public void remove() { // stringIterator.remove(); // } // // private static boolean isSwitch(final String argument) { // return SWITCH_PATTERN.matcher(argument).matches(); // } // // private boolean isArgumentEscape(final String value) { // return ("--".equals(value) && !argumentEscapeEncountered); // } // // private boolean isLongSwitch(final String value) { // return LONG_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private boolean isShortSwitchList(final String value) { // return SHORT_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private List<SwitchToken> splitSwitchTokens(final String value) { // final var tokens = new ArrayList<SwitchToken>(); // for (var i = 1; i < value.length(); i++) { // tokens.add(new SwitchToken(String.valueOf(value.charAt(i)), value)); // } // return tokens; // } // // } // // Path: src/main/java/com/github/jankroken/commandline/util/ArrayIterator.java // public class ArrayIterator<T> implements Iterator<T> { // // private final T[] array; // private int index = 0; // // public ArrayIterator(T[] array) { // this.array = array; // } // // public boolean hasNext() { // return array.length > index; // } // // public T next() { // if (array.length > index) { // return array[index++]; // } else { // throw new NoSuchElementException(); // } // } // // public T peek() { // if (array.length > index) { // return array[index]; // } else { // throw new NoSuchElementException(); // } // } // // public void remove() { // throw new UnsupportedOperationException(); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // }
import com.github.jankroken.commandline.domain.internal.LongOrCompactTokenizer; import com.github.jankroken.commandline.util.ArrayIterator; import com.github.jankroken.commandline.util.PeekIterator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat;
package com.github.jankroken.commandline.domain; public class LongOrCompactTokenizerTest { @Test public void simpleArgumentSplit() { final var args = new String[]{"-abcf", "hello.txt"};
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java // public class LongOrCompactTokenizer implements Tokenizer { // // private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); // private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); // private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); // private final PeekIterator<String> stringIterator; // private boolean argumentEscapeEncountered; // private String argumentTerminator; // private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); // // public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { // this.stringIterator = stringIterator; // } // // public void setArgumentTerminator(String argumentTerminator) { // this.argumentTerminator = argumentTerminator; // } // // public boolean hasNext() { // return stringIterator.hasNext(); // } // // // this is a mess - need to be cleaned up // public Token peek() { // if (!splitTokens.isEmpty()) { // return splitTokens.peek(); // } // final var value = stringIterator.peek(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return peek(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // var tokens = splitSwitchTokens(value); // return tokens.get(0); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // // this is a mess - needs to be cleaned up // public Token next() { // if (!splitTokens.isEmpty()) { // return splitTokens.remove(); // } // var value = stringIterator.next(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // argumentTerminator = null; // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return next(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // splitTokens.addAll(splitSwitchTokens(value)); // return splitTokens.remove(); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // public void remove() { // stringIterator.remove(); // } // // private static boolean isSwitch(final String argument) { // return SWITCH_PATTERN.matcher(argument).matches(); // } // // private boolean isArgumentEscape(final String value) { // return ("--".equals(value) && !argumentEscapeEncountered); // } // // private boolean isLongSwitch(final String value) { // return LONG_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private boolean isShortSwitchList(final String value) { // return SHORT_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private List<SwitchToken> splitSwitchTokens(final String value) { // final var tokens = new ArrayList<SwitchToken>(); // for (var i = 1; i < value.length(); i++) { // tokens.add(new SwitchToken(String.valueOf(value.charAt(i)), value)); // } // return tokens; // } // // } // // Path: src/main/java/com/github/jankroken/commandline/util/ArrayIterator.java // public class ArrayIterator<T> implements Iterator<T> { // // private final T[] array; // private int index = 0; // // public ArrayIterator(T[] array) { // this.array = array; // } // // public boolean hasNext() { // return array.length > index; // } // // public T next() { // if (array.length > index) { // return array[index++]; // } else { // throw new NoSuchElementException(); // } // } // // public T peek() { // if (array.length > index) { // return array[index]; // } else { // throw new NoSuchElementException(); // } // } // // public void remove() { // throw new UnsupportedOperationException(); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // } // Path: src/test/java/com/github/jankroken/commandline/domain/LongOrCompactTokenizerTest.java import com.github.jankroken.commandline.domain.internal.LongOrCompactTokenizer; import com.github.jankroken.commandline.util.ArrayIterator; import com.github.jankroken.commandline.util.PeekIterator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; package com.github.jankroken.commandline.domain; public class LongOrCompactTokenizerTest { @Test public void simpleArgumentSplit() { final var args = new String[]{"-abcf", "hello.txt"};
final var peekIterator = new PeekIterator<>(new ArrayIterator<>(args));
jankroken/commandline
src/test/java/com/github/jankroken/commandline/domain/LongOrCompactTokenizerTest.java
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java // public class LongOrCompactTokenizer implements Tokenizer { // // private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); // private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); // private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); // private final PeekIterator<String> stringIterator; // private boolean argumentEscapeEncountered; // private String argumentTerminator; // private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); // // public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { // this.stringIterator = stringIterator; // } // // public void setArgumentTerminator(String argumentTerminator) { // this.argumentTerminator = argumentTerminator; // } // // public boolean hasNext() { // return stringIterator.hasNext(); // } // // // this is a mess - need to be cleaned up // public Token peek() { // if (!splitTokens.isEmpty()) { // return splitTokens.peek(); // } // final var value = stringIterator.peek(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return peek(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // var tokens = splitSwitchTokens(value); // return tokens.get(0); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // // this is a mess - needs to be cleaned up // public Token next() { // if (!splitTokens.isEmpty()) { // return splitTokens.remove(); // } // var value = stringIterator.next(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // argumentTerminator = null; // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return next(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // splitTokens.addAll(splitSwitchTokens(value)); // return splitTokens.remove(); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // public void remove() { // stringIterator.remove(); // } // // private static boolean isSwitch(final String argument) { // return SWITCH_PATTERN.matcher(argument).matches(); // } // // private boolean isArgumentEscape(final String value) { // return ("--".equals(value) && !argumentEscapeEncountered); // } // // private boolean isLongSwitch(final String value) { // return LONG_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private boolean isShortSwitchList(final String value) { // return SHORT_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private List<SwitchToken> splitSwitchTokens(final String value) { // final var tokens = new ArrayList<SwitchToken>(); // for (var i = 1; i < value.length(); i++) { // tokens.add(new SwitchToken(String.valueOf(value.charAt(i)), value)); // } // return tokens; // } // // } // // Path: src/main/java/com/github/jankroken/commandline/util/ArrayIterator.java // public class ArrayIterator<T> implements Iterator<T> { // // private final T[] array; // private int index = 0; // // public ArrayIterator(T[] array) { // this.array = array; // } // // public boolean hasNext() { // return array.length > index; // } // // public T next() { // if (array.length > index) { // return array[index++]; // } else { // throw new NoSuchElementException(); // } // } // // public T peek() { // if (array.length > index) { // return array[index]; // } else { // throw new NoSuchElementException(); // } // } // // public void remove() { // throw new UnsupportedOperationException(); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // }
import com.github.jankroken.commandline.domain.internal.LongOrCompactTokenizer; import com.github.jankroken.commandline.util.ArrayIterator; import com.github.jankroken.commandline.util.PeekIterator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat;
package com.github.jankroken.commandline.domain; public class LongOrCompactTokenizerTest { @Test public void simpleArgumentSplit() { final var args = new String[]{"-abcf", "hello.txt"};
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java // public class LongOrCompactTokenizer implements Tokenizer { // // private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); // private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); // private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); // private final PeekIterator<String> stringIterator; // private boolean argumentEscapeEncountered; // private String argumentTerminator; // private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); // // public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { // this.stringIterator = stringIterator; // } // // public void setArgumentTerminator(String argumentTerminator) { // this.argumentTerminator = argumentTerminator; // } // // public boolean hasNext() { // return stringIterator.hasNext(); // } // // // this is a mess - need to be cleaned up // public Token peek() { // if (!splitTokens.isEmpty()) { // return splitTokens.peek(); // } // final var value = stringIterator.peek(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return peek(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // var tokens = splitSwitchTokens(value); // return tokens.get(0); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // // this is a mess - needs to be cleaned up // public Token next() { // if (!splitTokens.isEmpty()) { // return splitTokens.remove(); // } // var value = stringIterator.next(); // // if (argumentEscapeEncountered) { // return new ArgumentToken(value); // } // // if (Objects.equals(value, argumentTerminator)) { // argumentTerminator = null; // return new ArgumentToken(value); // } // if (argumentTerminator != null) { // return new ArgumentToken(value); // } // if (isArgumentEscape(value)) { // argumentEscapeEncountered = true; // return next(); // } // if (isSwitch(value)) { // if (isShortSwitchList(value)) { // splitTokens.addAll(splitSwitchTokens(value)); // return splitTokens.remove(); // } else { // return new SwitchToken(value.substring(2), value); // } // } else { // return new ArgumentToken(value); // } // } // // public void remove() { // stringIterator.remove(); // } // // private static boolean isSwitch(final String argument) { // return SWITCH_PATTERN.matcher(argument).matches(); // } // // private boolean isArgumentEscape(final String value) { // return ("--".equals(value) && !argumentEscapeEncountered); // } // // private boolean isLongSwitch(final String value) { // return LONG_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private boolean isShortSwitchList(final String value) { // return SHORT_STYLE_SWITCH_PATTERN.matcher(value).matches(); // } // // private List<SwitchToken> splitSwitchTokens(final String value) { // final var tokens = new ArrayList<SwitchToken>(); // for (var i = 1; i < value.length(); i++) { // tokens.add(new SwitchToken(String.valueOf(value.charAt(i)), value)); // } // return tokens; // } // // } // // Path: src/main/java/com/github/jankroken/commandline/util/ArrayIterator.java // public class ArrayIterator<T> implements Iterator<T> { // // private final T[] array; // private int index = 0; // // public ArrayIterator(T[] array) { // this.array = array; // } // // public boolean hasNext() { // return array.length > index; // } // // public T next() { // if (array.length > index) { // return array[index++]; // } else { // throw new NoSuchElementException(); // } // } // // public T peek() { // if (array.length > index) { // return array[index]; // } else { // throw new NoSuchElementException(); // } // } // // public void remove() { // throw new UnsupportedOperationException(); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // } // Path: src/test/java/com/github/jankroken/commandline/domain/LongOrCompactTokenizerTest.java import com.github.jankroken.commandline.domain.internal.LongOrCompactTokenizer; import com.github.jankroken.commandline.util.ArrayIterator; import com.github.jankroken.commandline.util.PeekIterator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; package com.github.jankroken.commandline.domain; public class LongOrCompactTokenizerTest { @Test public void simpleArgumentSplit() { final var args = new String[]{"-abcf", "hello.txt"};
final var peekIterator = new PeekIterator<>(new ArrayIterator<>(args));
jankroken/commandline
src/test/java/com/github/jankroken/commandline/happy/LongOrCompactParserTest.java
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // }
import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.LONG_OR_COMPACT; import static org.assertj.core.api.Assertions.assertThat;
package com.github.jankroken.commandline.happy; public class LongOrCompactParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-vf", "hello.txt"};
// Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // Path: src/test/java/com/github/jankroken/commandline/happy/LongOrCompactParserTest.java import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.LONG_OR_COMPACT; import static org.assertj.core.api.Assertions.assertThat; package com.github.jankroken.commandline.happy; public class LongOrCompactParserTest { @Test public void testSimpleConfiguration() throws Exception { final var args = new String[]{"-vf", "hello.txt"};
final var config = parse(SimpleConfiguration.class, args, LONG_OR_COMPACT);
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSet.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // }
import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import java.lang.reflect.InvocationTargetException; import java.util.List;
this.optionSetLevel = optionSetLevel; this.spec = spec; } public OptionSpecification getOptionSpecification(SwitchToken _switch) { for (final var optionSpecification : options) { if (optionSpecification.getSwitch().matches(_switch.getValue())) { return optionSpecification; } } return null; } public OptionSpecification getLooseArgsOptionSpecification() { for (final var optionSpecification : options) { if (optionSpecification.isLooseArgumentsSpecification()) { return optionSpecification; } } return null; } public void consumeOptions(Tokenizer args) throws IllegalAccessException, InvocationTargetException, InstantiationException { while (args.hasNext()) { if (args.peek() instanceof SwitchToken) { var optionSpecification = getOptionSpecification((SwitchToken) args.peek()); if (optionSpecification == null) { switch (optionSetLevel) { case MAIN_OPTIONS:
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSet.java import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import java.lang.reflect.InvocationTargetException; import java.util.List; this.optionSetLevel = optionSetLevel; this.spec = spec; } public OptionSpecification getOptionSpecification(SwitchToken _switch) { for (final var optionSpecification : options) { if (optionSpecification.getSwitch().matches(_switch.getValue())) { return optionSpecification; } } return null; } public OptionSpecification getLooseArgsOptionSpecification() { for (final var optionSpecification : options) { if (optionSpecification.isLooseArgumentsSpecification()) { return optionSpecification; } } return null; } public void consumeOptions(Tokenizer args) throws IllegalAccessException, InvocationTargetException, InstantiationException { while (args.hasNext()) { if (args.peek() instanceof SwitchToken) { var optionSpecification = getOptionSpecification((SwitchToken) args.peek()); if (optionSpecification == null) { switch (optionSetLevel) { case MAIN_OPTIONS:
throw new UnrecognizedSwitchException(spec.getClass(), args.peek().getValue());
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSet.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // }
import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import java.lang.reflect.InvocationTargetException; import java.util.List;
return optionSpecification; } } return null; } public void consumeOptions(Tokenizer args) throws IllegalAccessException, InvocationTargetException, InstantiationException { while (args.hasNext()) { if (args.peek() instanceof SwitchToken) { var optionSpecification = getOptionSpecification((SwitchToken) args.peek()); if (optionSpecification == null) { switch (optionSetLevel) { case MAIN_OPTIONS: throw new UnrecognizedSwitchException(spec.getClass(), args.peek().getValue()); case SUB_GROUP: validateAndConsolidate(); return; } } else { args.next(); optionSpecification.activateAndConsumeArguments(args); } } else { var looseArgsOptionSpecification = getLooseArgsOptionSpecification(); if (looseArgsOptionSpecification != null) { looseArgsOptionSpecification.activateAndConsumeArguments(args); } else { switch (optionSetLevel) { case MAIN_OPTIONS:
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSet.java import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import java.lang.reflect.InvocationTargetException; import java.util.List; return optionSpecification; } } return null; } public void consumeOptions(Tokenizer args) throws IllegalAccessException, InvocationTargetException, InstantiationException { while (args.hasNext()) { if (args.peek() instanceof SwitchToken) { var optionSpecification = getOptionSpecification((SwitchToken) args.peek()); if (optionSpecification == null) { switch (optionSetLevel) { case MAIN_OPTIONS: throw new UnrecognizedSwitchException(spec.getClass(), args.peek().getValue()); case SUB_GROUP: validateAndConsolidate(); return; } } else { args.next(); optionSpecification.activateAndConsumeArguments(args); } } else { var looseArgsOptionSpecification = getLooseArgsOptionSpecification(); if (looseArgsOptionSpecification != null) { looseArgsOptionSpecification.activateAndConsumeArguments(args); } else { switch (optionSetLevel) { case MAIN_OPTIONS:
throw new InvalidCommandLineException("Invalid argument: " + args.peek());
jankroken/commandline
src/test/java/com/github/jankroken/commandline/domain/OptionSpecificationFactoryTest.java
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecificationFactory.java // public class OptionSpecificationFactory { // // // public static OptionSpecification getOptionSpecification(Object spec, Method method) { // var builder = new OptionSpecificationBuilder(); // builder.addMethod(method); // builder.addConfiguration(spec); // for (var annotation : method.getAnnotations()) { // if (annotation instanceof Option) { // } else if (annotation instanceof LongSwitch) { // builder.addLongSwitch(((LongSwitch) annotation).value()); // } else if (annotation instanceof ShortSwitch) { // builder.addShortSwitch(((ShortSwitch) annotation).value()); // } else if (annotation instanceof Toggle) { // builder.addToggle(((Toggle) annotation).value()); // } else if (annotation instanceof SingleArgument) { // builder.addSingleArgument(); // } else if (annotation instanceof AllAvailableArguments) { // builder.addAllAvailableArguments(); // } else if (annotation instanceof ArgumentsUntilDelimiter) { // builder.addUntilDelimiter(((ArgumentsUntilDelimiter) annotation).value()); // } else if (annotation instanceof SubConfiguration) { // builder.addSubset(((SubConfiguration) annotation).value()); // } else if (annotation instanceof Required) { // builder.addRequired(); // } else if (annotation instanceof Multiple) { // builder.addOccurrences(Occurrences.MULTIPLE); // } else if (annotation instanceof LooseArguments) { // builder.addLooseArgs(); // } else { // // todo // System.out.println("Unhandled annotation: " + annotation); // } // } // return builder.getOptionSpecification(); // // } // // public static List<OptionSpecification> getOptionSpecifications(Object spec, Class<?> optionClass) { // var methods = new Methods(optionClass).byAnnotation(Option.class); // List<OptionSpecification> optionSpecifications = new ArrayList<>(); // for (var method : methods) { // optionSpecifications.add(getOptionSpecification(spec, method)); // } // return optionSpecifications; // } // }
import com.github.jankroken.commandline.domain.internal.OptionSpecificationFactory; import com.github.jankroken.commandline.happy.SimpleConfiguration; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
package com.github.jankroken.commandline.domain; public class OptionSpecificationFactoryTest { @Test public void testOptionSpecificationFactory() { var conf = new SimpleConfiguration();
// Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecificationFactory.java // public class OptionSpecificationFactory { // // // public static OptionSpecification getOptionSpecification(Object spec, Method method) { // var builder = new OptionSpecificationBuilder(); // builder.addMethod(method); // builder.addConfiguration(spec); // for (var annotation : method.getAnnotations()) { // if (annotation instanceof Option) { // } else if (annotation instanceof LongSwitch) { // builder.addLongSwitch(((LongSwitch) annotation).value()); // } else if (annotation instanceof ShortSwitch) { // builder.addShortSwitch(((ShortSwitch) annotation).value()); // } else if (annotation instanceof Toggle) { // builder.addToggle(((Toggle) annotation).value()); // } else if (annotation instanceof SingleArgument) { // builder.addSingleArgument(); // } else if (annotation instanceof AllAvailableArguments) { // builder.addAllAvailableArguments(); // } else if (annotation instanceof ArgumentsUntilDelimiter) { // builder.addUntilDelimiter(((ArgumentsUntilDelimiter) annotation).value()); // } else if (annotation instanceof SubConfiguration) { // builder.addSubset(((SubConfiguration) annotation).value()); // } else if (annotation instanceof Required) { // builder.addRequired(); // } else if (annotation instanceof Multiple) { // builder.addOccurrences(Occurrences.MULTIPLE); // } else if (annotation instanceof LooseArguments) { // builder.addLooseArgs(); // } else { // // todo // System.out.println("Unhandled annotation: " + annotation); // } // } // return builder.getOptionSpecification(); // // } // // public static List<OptionSpecification> getOptionSpecifications(Object spec, Class<?> optionClass) { // var methods = new Methods(optionClass).byAnnotation(Option.class); // List<OptionSpecification> optionSpecifications = new ArrayList<>(); // for (var method : methods) { // optionSpecifications.add(getOptionSpecification(spec, method)); // } // return optionSpecifications; // } // } // Path: src/test/java/com/github/jankroken/commandline/domain/OptionSpecificationFactoryTest.java import com.github.jankroken.commandline.domain.internal.OptionSpecificationFactory; import com.github.jankroken.commandline.happy.SimpleConfiguration; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; package com.github.jankroken.commandline.domain; public class OptionSpecificationFactoryTest { @Test public void testOptionSpecificationFactory() { var conf = new SimpleConfiguration();
var specifications = OptionSpecificationFactory.getOptionSpecifications(conf, conf.getClass());
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // }
import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern;
package com.github.jankroken.commandline.domain.internal; public class LongOrCompactTokenizer implements Tokenizer { private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*");
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; package com.github.jankroken.commandline.domain.internal; public class LongOrCompactTokenizer implements Tokenizer { private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*");
private final PeekIterator<String> stringIterator;
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // }
import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern;
package com.github.jankroken.commandline.domain.internal; public class LongOrCompactTokenizer implements Tokenizer { private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); private final PeekIterator<String> stringIterator; private boolean argumentEscapeEncountered; private String argumentTerminator; private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { this.stringIterator = stringIterator; } public void setArgumentTerminator(String argumentTerminator) { this.argumentTerminator = argumentTerminator; } public boolean hasNext() { return stringIterator.hasNext(); } // this is a mess - need to be cleaned up public Token peek() { if (!splitTokens.isEmpty()) { return splitTokens.peek(); } final var value = stringIterator.peek(); if (argumentEscapeEncountered) {
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/LongOrCompactTokenizer.java import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; package com.github.jankroken.commandline.domain.internal; public class LongOrCompactTokenizer implements Tokenizer { private static final Pattern SWITCH_PATTERN = Pattern.compile("-.*"); private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile("--..*"); private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile("-[^-].*"); private final PeekIterator<String> stringIterator; private boolean argumentEscapeEncountered; private String argumentTerminator; private final LinkedList<SwitchToken> splitTokens = new LinkedList<>(); public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) { this.stringIterator = stringIterator; } public void setArgumentTerminator(String argumentTerminator) { this.argumentTerminator = argumentTerminator; } public boolean hasNext() { return stringIterator.hasNext(); } // this is a mess - need to be cleaned up public Token peek() { if (!splitTokens.isEmpty()) { return splitTokens.peek(); } final var value = stringIterator.peek(); if (argumentEscapeEncountered) {
return new ArgumentToken(value);
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionBuilder.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionType.java // public enum ArgumentConsumptionType { // NO_ARGS, // SINGLE_ARGUMENT, // ALL_AVAILABLE, // UNTIL_DELIMITER, // SUB_SET, // LOOSE_ARGS // }
import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import static com.github.jankroken.commandline.domain.internal.ArgumentConsumptionType.*;
single_argument = true; } public void addUntilDelimiter(String delimiter) { until_delimiter = true; this.delimiter = delimiter; } public void addAllAvailable() { all_available = true; } public void addLooseArgs() { loose_args = true; } public void addSubSet(Class<?> subsetClass) { this.sub_set = true; this.subsetClass = subsetClass; } public ArgumentConsumption getArgumentConsumption() { var argumentConsumptionTypeCounter = 0; if (no_arguments) argumentConsumptionTypeCounter++; if (single_argument) argumentConsumptionTypeCounter++; if (until_delimiter) argumentConsumptionTypeCounter++; if (all_available) argumentConsumptionTypeCounter++; if (sub_set) argumentConsumptionTypeCounter++; if (loose_args) argumentConsumptionTypeCounter++; if (argumentConsumptionTypeCounter == 0) {
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionType.java // public enum ArgumentConsumptionType { // NO_ARGS, // SINGLE_ARGUMENT, // ALL_AVAILABLE, // UNTIL_DELIMITER, // SUB_SET, // LOOSE_ARGS // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionBuilder.java import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import static com.github.jankroken.commandline.domain.internal.ArgumentConsumptionType.*; single_argument = true; } public void addUntilDelimiter(String delimiter) { until_delimiter = true; this.delimiter = delimiter; } public void addAllAvailable() { all_available = true; } public void addLooseArgs() { loose_args = true; } public void addSubSet(Class<?> subsetClass) { this.sub_set = true; this.subsetClass = subsetClass; } public ArgumentConsumption getArgumentConsumption() { var argumentConsumptionTypeCounter = 0; if (no_arguments) argumentConsumptionTypeCounter++; if (single_argument) argumentConsumptionTypeCounter++; if (until_delimiter) argumentConsumptionTypeCounter++; if (all_available) argumentConsumptionTypeCounter++; if (sub_set) argumentConsumptionTypeCounter++; if (loose_args) argumentConsumptionTypeCounter++; if (argumentConsumptionTypeCounter == 0) {
throw new InvalidOptionConfigurationException("No argument consumption type specified");
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionBuilder.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionType.java // public enum ArgumentConsumptionType { // NO_ARGS, // SINGLE_ARGUMENT, // ALL_AVAILABLE, // UNTIL_DELIMITER, // SUB_SET, // LOOSE_ARGS // }
import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import static com.github.jankroken.commandline.domain.internal.ArgumentConsumptionType.*;
if (single_argument) argumentConsumptionTypeCounter++; if (until_delimiter) argumentConsumptionTypeCounter++; if (all_available) argumentConsumptionTypeCounter++; if (sub_set) argumentConsumptionTypeCounter++; if (loose_args) argumentConsumptionTypeCounter++; if (argumentConsumptionTypeCounter == 0) { throw new InvalidOptionConfigurationException("No argument consumption type specified"); } if (argumentConsumptionTypeCounter > 1) { throw new InvalidOptionConfigurationException("Multiple argument consumption types specified"); } if (no_arguments) { return new ArgumentConsumption(NO_ARGS, toggle_value); } if (single_argument) { return new ArgumentConsumption(SINGLE_ARGUMENT); } if (until_delimiter) { return new ArgumentConsumption(UNTIL_DELIMITER, delimiter); } if (all_available) { return new ArgumentConsumption(ALL_AVAILABLE); } if (sub_set) { return new ArgumentConsumption(SUB_SET, subsetClass); } if (loose_args) { return new ArgumentConsumption(LOOSE_ARGS); }
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionType.java // public enum ArgumentConsumptionType { // NO_ARGS, // SINGLE_ARGUMENT, // ALL_AVAILABLE, // UNTIL_DELIMITER, // SUB_SET, // LOOSE_ARGS // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/ArgumentConsumptionBuilder.java import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import static com.github.jankroken.commandline.domain.internal.ArgumentConsumptionType.*; if (single_argument) argumentConsumptionTypeCounter++; if (until_delimiter) argumentConsumptionTypeCounter++; if (all_available) argumentConsumptionTypeCounter++; if (sub_set) argumentConsumptionTypeCounter++; if (loose_args) argumentConsumptionTypeCounter++; if (argumentConsumptionTypeCounter == 0) { throw new InvalidOptionConfigurationException("No argument consumption type specified"); } if (argumentConsumptionTypeCounter > 1) { throw new InvalidOptionConfigurationException("Multiple argument consumption types specified"); } if (no_arguments) { return new ArgumentConsumption(NO_ARGS, toggle_value); } if (single_argument) { return new ArgumentConsumption(SINGLE_ARGUMENT); } if (until_delimiter) { return new ArgumentConsumption(UNTIL_DELIMITER, delimiter); } if (all_available) { return new ArgumentConsumption(ALL_AVAILABLE); } if (sub_set) { return new ArgumentConsumption(SUB_SET, subsetClass); } if (loose_args) { return new ArgumentConsumption(LOOSE_ARGS); }
throw new InternalErrorException("Internal error: no matching argument consumption types");
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/SimpleTokenizer.java
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // }
import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.Objects;
package com.github.jankroken.commandline.domain.internal; public class SimpleTokenizer implements Tokenizer { private final PeekIterator<String> stringIterator; private boolean argumentEscapeEncountered; private String argumentTerminator; public SimpleTokenizer(PeekIterator<String> stringIterator) { this.stringIterator = stringIterator; } public void setArgumentTerminator(String argumentTerminator) { this.argumentTerminator = argumentTerminator; } public boolean hasNext() { return stringIterator.hasNext(); } public Token peek() { final var value = stringIterator.peek(); return makeToken(value); } public Token next() { final var value = stringIterator.next(); return makeToken(value); } private Token makeToken(String value) { if (Objects.equals(value, argumentTerminator)) { argumentTerminator = null;
// Path: src/main/java/com/github/jankroken/commandline/domain/ArgumentToken.java // public class ArgumentToken implements Token { // private final String value; // // public ArgumentToken(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // // public String getArgumentValue() { // return value; // } // // @Override // public String toString() { // return "<ArgumentToken:" + value + ">"; // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/PeekIterator.java // public class PeekIterator<T> implements Iterator<T> { // // private T nextValue; // private final Iterator<T> iterator; // // public PeekIterator(Iterator<T> iterator) { // this.iterator = iterator; // } // // public boolean hasNext() { // return nextValue != null || iterator.hasNext(); // } // // public T next() { // if (nextValue != null) { // var value = nextValue; // nextValue = null; // return value; // } else { // return iterator.next(); // } // } // // public T peek() { // if (nextValue == null) { // nextValue = iterator.next(); // } // return nextValue; // } // // public void remove() { // throw new UnsupportedOperationException(); // } // // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/SimpleTokenizer.java import com.github.jankroken.commandline.domain.ArgumentToken; import com.github.jankroken.commandline.util.PeekIterator; import java.util.Objects; package com.github.jankroken.commandline.domain.internal; public class SimpleTokenizer implements Tokenizer { private final PeekIterator<String> stringIterator; private boolean argumentEscapeEncountered; private String argumentTerminator; public SimpleTokenizer(PeekIterator<String> stringIterator) { this.stringIterator = stringIterator; } public void setArgumentTerminator(String argumentTerminator) { this.argumentTerminator = argumentTerminator; } public boolean hasNext() { return stringIterator.hasNext(); } public Token peek() { final var value = stringIterator.peek(); return makeToken(value); } public Token next() { final var value = stringIterator.next(); return makeToken(value); } private Token makeToken(String value) { if (Objects.equals(value, argumentTerminator)) { argumentTerminator = null;
return new ArgumentToken(value);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/util/PeekIteratorTest.java
// Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.*;
package com.github.jankroken.commandline.util; public class PeekIteratorTest { private static PeekIterator<String> createIterator(String[] args) { var ai = new ArrayIterator<>(args); return new PeekIterator<>(ai); } @Test public void testEmpty() {
// Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/util/PeekIteratorTest.java import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.*; package com.github.jankroken.commandline.util; public class PeekIteratorTest { private static PeekIterator<String> createIterator(String[] args) { var ai = new ArrayIterator<>(args); return new PeekIterator<>(ai); } @Test public void testEmpty() {
var ai = createIterator(EMPTY_STRING_ARRAY);
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() {
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() {
assertThatThrownBy(() -> parse(MissingSwitchesConfiguration.class, EMPTY_STRING_ARRAY, SIMPLE))
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() {
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() {
assertThatThrownBy(() -> parse(MissingSwitchesConfiguration.class, EMPTY_STRING_ARRAY, SIMPLE))
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() { assertThatThrownBy(() -> parse(MissingSwitchesConfiguration.class, EMPTY_STRING_ARRAY, SIMPLE))
// Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidConfigurationTests.java import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidConfigurationTests { @Test public void testMissingSwitches() { assertThatThrownBy(() -> parse(MissingSwitchesConfiguration.class, EMPTY_STRING_ARRAY, SIMPLE))
.isInstanceOf(InvalidOptionConfigurationException.class);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/model/SendTask.java
// Path: src/main/java/com/ystruct.middleware/stormmq/smq/Message.java // public class Message implements Serializable{ // //private static final long serialVersionUID = 5295808332504208830L; // private String topic; // private byte[] body; // private String msgId; // private long bornTime; // private Map<String,String> properties = new HashMap<String, String>(); // // public String getTopic() { // return topic; // } // // public void setTopic(String topic) { // this.topic = topic; // } // // public byte[] getBody() { // return body; // } // // public void setBody(byte[] body) { // this.body = body; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public long getBornTime() { // return bornTime; // } // // public void setBornTime(long bornTime) { // this.bornTime = bornTime; // } // // public Map<String, String> getProperties() { // return properties; // } // // public void setProperties(Map<String, String> properties) { // this.properties = properties; // } // public String getProperty(String key){ // return (String)this.properties.get(key); // } // public void setProperty(String key,String value){ // this.properties.put(key,value); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Message other=(Message)obj; // if(topic == null){ // if(other.getTopic() != null) // return false; // }else{ // if(other.getTopic() == null) // return false; // else if(!other.getTopic().equals(topic)) // return false; // } // if(body == null){ // if(other.getBody() != null) // return false; // }else{ // if(other.getBody() == null) // return false; // if(body.length != other.getBody().length) // return false; // else // for(int i = 0;i < body.length; ++i){ // if(body[i] != other.getBody()[i]) // return false; // } // } // // if(properties==null) // { // if(other.getProperties()!=null) // return false; // } // else // { // if(other.getProperties()==null) // return false; // else if(!properties.equals(other.getProperties())) // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = topic.hashCode(); // result += properties.hashCode(); // if(body != null) // for(int i = 0; i < body.length; ++i){ // result += body[i]; // } // return result; // } // }
import smq.Message; import java.io.Serializable;
package model; /** * Created by yang on 16-11-26. */ public class SendTask implements Serializable { private String groupId; //组id private String topic; //主题
// Path: src/main/java/com/ystruct.middleware/stormmq/smq/Message.java // public class Message implements Serializable{ // //private static final long serialVersionUID = 5295808332504208830L; // private String topic; // private byte[] body; // private String msgId; // private long bornTime; // private Map<String,String> properties = new HashMap<String, String>(); // // public String getTopic() { // return topic; // } // // public void setTopic(String topic) { // this.topic = topic; // } // // public byte[] getBody() { // return body; // } // // public void setBody(byte[] body) { // this.body = body; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public long getBornTime() { // return bornTime; // } // // public void setBornTime(long bornTime) { // this.bornTime = bornTime; // } // // public Map<String, String> getProperties() { // return properties; // } // // public void setProperties(Map<String, String> properties) { // this.properties = properties; // } // public String getProperty(String key){ // return (String)this.properties.get(key); // } // public void setProperty(String key,String value){ // this.properties.put(key,value); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Message other=(Message)obj; // if(topic == null){ // if(other.getTopic() != null) // return false; // }else{ // if(other.getTopic() == null) // return false; // else if(!other.getTopic().equals(topic)) // return false; // } // if(body == null){ // if(other.getBody() != null) // return false; // }else{ // if(other.getBody() == null) // return false; // if(body.length != other.getBody().length) // return false; // else // for(int i = 0;i < body.length; ++i){ // if(body[i] != other.getBody()[i]) // return false; // } // } // // if(properties==null) // { // if(other.getProperties()!=null) // return false; // } // else // { // if(other.getProperties()==null) // return false; // else if(!properties.equals(other.getProperties())) // return false; // } // // return true; // } // // @Override // public int hashCode() { // int result = topic.hashCode(); // result += properties.hashCode(); // if(body != null) // for(int i = 0; i < body.length; ++i){ // result += body[i]; // } // return result; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/model/SendTask.java import smq.Message; import java.io.Serializable; package model; /** * Created by yang on 16-11-26. */ public class SendTask implements Serializable { private String groupId; //组id private String topic; //主题
private Message message;
liuhangyang/StormMQ
src/main/test/DirectByteBuffer/directBytebuffer.java
// Path: src/main/java/com/ystruct.middleware/stormmq/store/MapedFile.java // public static void clean(final ByteBuffer buffer) { // if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0) // return; // invoke(invoke(viewed(buffer), "cleaner"), "clean"); // // }
import java.nio.ByteBuffer; import static store.MapedFile.clean;
package DirectByteBuffer; /** * Created by yang on 16-11-27. */ public class directBytebuffer { public static void sleep(long i){ try { Thread.sleep(i); }catch (Exception e){ } } public static void main(String[] args) throws Exception{ ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*500); System.out.println("start"); sleep(10000);
// Path: src/main/java/com/ystruct.middleware/stormmq/store/MapedFile.java // public static void clean(final ByteBuffer buffer) { // if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0) // return; // invoke(invoke(viewed(buffer), "cleaner"), "clean"); // // } // Path: src/main/test/DirectByteBuffer/directBytebuffer.java import java.nio.ByteBuffer; import static store.MapedFile.clean; package DirectByteBuffer; /** * Created by yang on 16-11-27. */ public class directBytebuffer { public static void sleep(long i){ try { Thread.sleep(i); }catch (Exception e){ } } public static void main(String[] args) throws Exception{ ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*500); System.out.println("start"); sleep(10000);
clean(buffer);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // }
import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest;
package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler);
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // } // Path: src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest; package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler);
Object Send(StormRequest request);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // }
import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest;
package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler); Object Send(StormRequest request);
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // } // Path: src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest; package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler); Object Send(StormRequest request);
void Send(StormRequest request, final SendCallback listener);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // }
import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest;
package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler); Object Send(StormRequest request); void Send(StormRequest request, final SendCallback listener); void close(); boolean isConnected(); boolean isClosed(); public boolean ContrainsFuture(String key);
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendCallback.java // public abstract interface SendCallback { // public abstract void onResult(SendResult papramSendResult); // } // Path: src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormProducerConnection.java import smq.SendCallback; import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest; package producer.netty; /** * Created by yang on 16-11-22. */ /** * producer和broker之间的连接. */ public interface StormProducerConnection { void init(); void connect(); void connect(String host,int port); void setHandler(ChannelInboundHandlerAdapter handler); Object Send(StormRequest request); void Send(StormRequest request, final SendCallback listener); void close(); boolean isConnected(); boolean isClosed(); public boolean ContrainsFuture(String key);
public InvokeFuture<Object> removeFuture(String key);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormHandler.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // }
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ConnectTimeoutException; import model.InvokeFuture; import model.StormResponse;
package producer.netty; /** * Created by yang on 16-11-22. */ public class StormHandler extends ChannelInboundHandlerAdapter{ private StormProducerConnection connect; private Throwable cause; private ConnectListener listener; public StormHandler(){ } public StormHandler(StormProducerConnection conn){ this.connect = conn; } public StormHandler(StormProducerConnection conn, ConnectListener listener) { this.connect = conn; this.listener = listener; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception{ super.channelActive(ctx); System.out.println("connected on server: "+ ctx.channel().remoteAddress().toString()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("channelRead");
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormHandler.java import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ConnectTimeoutException; import model.InvokeFuture; import model.StormResponse; package producer.netty; /** * Created by yang on 16-11-22. */ public class StormHandler extends ChannelInboundHandlerAdapter{ private StormProducerConnection connect; private Throwable cause; private ConnectListener listener; public StormHandler(){ } public StormHandler(StormProducerConnection conn){ this.connect = conn; } public StormHandler(StormProducerConnection conn, ConnectListener listener) { this.connect = conn; this.listener = listener; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception{ super.channelActive(ctx); System.out.println("connected on server: "+ ctx.channel().remoteAddress().toString()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("channelRead");
StormResponse response = (StormResponse)msg;
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormHandler.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // }
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ConnectTimeoutException; import model.InvokeFuture; import model.StormResponse;
package producer.netty; /** * Created by yang on 16-11-22. */ public class StormHandler extends ChannelInboundHandlerAdapter{ private StormProducerConnection connect; private Throwable cause; private ConnectListener listener; public StormHandler(){ } public StormHandler(StormProducerConnection conn){ this.connect = conn; } public StormHandler(StormProducerConnection conn, ConnectListener listener) { this.connect = conn; this.listener = listener; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception{ super.channelActive(ctx); System.out.println("connected on server: "+ ctx.channel().remoteAddress().toString()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("channelRead"); StormResponse response = (StormResponse)msg; String key = response.getRequestId(); if(connect.ContrainsFuture(key)){
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/producer/netty/StormHandler.java import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ConnectTimeoutException; import model.InvokeFuture; import model.StormResponse; package producer.netty; /** * Created by yang on 16-11-22. */ public class StormHandler extends ChannelInboundHandlerAdapter{ private StormProducerConnection connect; private Throwable cause; private ConnectListener listener; public StormHandler(){ } public StormHandler(StormProducerConnection conn){ this.connect = conn; } public StormHandler(StormProducerConnection conn, ConnectListener listener) { this.connect = conn; this.listener = listener; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception{ super.channelActive(ctx); System.out.println("connected on server: "+ ctx.channel().remoteAddress().toString()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("channelRead"); StormResponse response = (StormResponse)msg; String key = response.getRequestId(); if(connect.ContrainsFuture(key)){
InvokeFuture<Object> future = connect.removeFuture(key);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerConnection.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // }
import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest;
package consumer.netty; /** * Created by yang on 16-11-24. */ public interface StormConsumerConnection { void init(); void connect(); void connect(String host,int port); void sethandle(ChannelInboundHandlerAdapter hanler);
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerConnection.java import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest; package consumer.netty; /** * Created by yang on 16-11-24. */ public interface StormConsumerConnection { void init(); void connect(); void connect(String host,int port); void sethandle(ChannelInboundHandlerAdapter hanler);
Object Send(StormRequest request);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerConnection.java
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // }
import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest;
package consumer.netty; /** * Created by yang on 16-11-24. */ public interface StormConsumerConnection { void init(); void connect(); void connect(String host,int port); void sethandle(ChannelInboundHandlerAdapter hanler); Object Send(StormRequest request); void SendSync(StormRequest request); void close(); boolean isConnected(); boolean isClosed(); public boolean ContainsFuture(String key);
// Path: src/main/java/com/ystruct.middleware/stormmq/model/InvokeFuture.java // public class InvokeFuture<T> { // private Semaphore semaphore = new Semaphore(0); // private T result; // private List<InvokeListener<T>> listeners = new ArrayList<InvokeListener<T>>(); // private String requestId; // private Throwable cause; // public void setCause(Throwable cause){ // this.cause = cause; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // // } // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public InvokeFuture() { // } // // public void setResult(T result) { // this.result=result; // notifyListeners(); // semaphore.release(Integer.MAX_VALUE - semaphore.availablePermits()); // } // public Object getResult(long timeout,TimeUnit unit){ // try { // if(!semaphore.tryAcquire(timeout,unit)){ // throw new RuntimeException("time out"); // } // }catch (InterruptedException e){ // throw new RuntimeException(); // } // if(cause != null) // return null; // return result; // } // public void addInvokerListener(InvokeListener<T> listener){ // this.listeners.add(listener); // } // private void notifyListeners(){ // for(InvokeListener<T> listener : listeners){ // listener.onResponse(result); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormRequest.java // public class StormRequest implements Serializable { // //一次请求的id // private String requestId; // //请求的参数 // private Object parameters; // //消息是从哪里来的 // private RequestResponseFromType fromType; // //请求的类型 // private RequestType requestType; // // public RequestType getRequestType() { // return requestType; // } // public void setRequestType(RequestType requestType) { // this.requestType = requestType; // } // public RequestResponseFromType getFromType() { // return fromType; // } // public void setFromType(RequestResponseFromType fromType) { // this.fromType = fromType; // } // public String getRequestId() { // return requestId; // } // public void setRequestId(String requestId) { // this.requestId = requestId; // } // public Object getParameters() { // return parameters; // } // public void setParameters(Object parameters) { // this.parameters = parameters; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerConnection.java import io.netty.channel.ChannelInboundHandlerAdapter; import model.InvokeFuture; import model.StormRequest; package consumer.netty; /** * Created by yang on 16-11-24. */ public interface StormConsumerConnection { void init(); void connect(); void connect(String host,int port); void sethandle(ChannelInboundHandlerAdapter hanler); Object Send(StormRequest request); void SendSync(StormRequest request); void close(); boolean isConnected(); boolean isClosed(); public boolean ContainsFuture(String key);
public InvokeFuture<Object> removeFuture(String key);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerHandler.java
// Path: src/main/java/com/ystruct.middleware/stormmq/smq/ConsumeResult.java // public class ConsumeResult { // private ConsumeStatus status = ConsumeStatus.FAIL; // private String info; // private String groupID; // private String topic; // private String msgId; // // public ConsumeStatus getStatus() { // return status; // } // // public void setStatus(ConsumeStatus status) { // this.status = status; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public String getGroupID() { // return groupID; // } // // public void setGroupID(String groupID) { // this.groupID = groupID; // } // // public String getTopic() { // return topic; // } // // public void setTopic(String topic) { // this.topic = topic; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // }
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import model.*; import smq.ConsumeResult;
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("收到消息"); StormResponse response = (StormResponse)msg; String key = response.getRequestId(); if(connect.ContainsFuture(key)){ InvokeFuture<Object> future = connect.removeFuture(key); //没有找到对应的发送请求,则返回 if(future == null){ return; } if(this.cause != null){ //设置异常结果,会触发里面的回调函数 // System.out.println("StormConr sumerHandler:::-->cause:"+cause); future.setCause(cause); if(listener != null) listener.onException(cause); }else { future.setResult(response); } }else { //如果不是consumer主动发送的数据,则说明是服务器主动发送的消息,则调用消息收到 if(listener != null){
// Path: src/main/java/com/ystruct.middleware/stormmq/smq/ConsumeResult.java // public class ConsumeResult { // private ConsumeStatus status = ConsumeStatus.FAIL; // private String info; // private String groupID; // private String topic; // private String msgId; // // public ConsumeStatus getStatus() { // return status; // } // // public void setStatus(ConsumeStatus status) { // this.status = status; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public String getGroupID() { // return groupID; // } // // public void setGroupID(String groupID) { // this.groupID = groupID; // } // // public String getTopic() { // return topic; // } // // public void setTopic(String topic) { // this.topic = topic; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/consumer/netty/StormConsumerHandler.java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import model.*; import smq.ConsumeResult; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("收到消息"); StormResponse response = (StormResponse)msg; String key = response.getRequestId(); if(connect.ContainsFuture(key)){ InvokeFuture<Object> future = connect.removeFuture(key); //没有找到对应的发送请求,则返回 if(future == null){ return; } if(this.cause != null){ //设置异常结果,会触发里面的回调函数 // System.out.println("StormConr sumerHandler:::-->cause:"+cause); future.setCause(cause); if(listener != null) listener.onException(cause); }else { future.setResult(response); } }else { //如果不是consumer主动发送的数据,则说明是服务器主动发送的消息,则调用消息收到 if(listener != null){
ConsumeResult result = (ConsumeResult)listener.onResponse(response);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // }
import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult;
package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack");
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // } // Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult; package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack");
SemaphoreManager.descrease("Ack");//获取一个ACK的信号量
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // }
import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult;
package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack"); SemaphoreManager.descrease("Ack");//获取一个ACK的信号量 // System.out.println("得到一个ack1"); //获取ack消息
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // } // Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult; package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack"); SemaphoreManager.descrease("Ack");//获取一个ACK的信号量 // System.out.println("得到一个ack1"); //获取ack消息
SendResult ack = AckManager.getAck();
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // }
import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult;
package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack"); SemaphoreManager.descrease("Ack");//获取一个ACK的信号量 // System.out.println("得到一个ack1"); //获取ack消息
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/AckManager.java // public class AckManager { // //ConcurrentLinkedQueue是一个非阻塞的线程安全的队列,注意不要使用ConcurrentLinkQueue的size()方法,此方法会遍历所有的元素 // private static ConcurrentLinkedQueue<SendResult> ackQueue = new ConcurrentLinkedQueue<SendResult>(); // private static ConcurrentHashMap<String/*requestId*/,Channel> producerMap = new ConcurrentHashMap<String, Channel>(); // // public static void pushRequest(String requestId,Channel channel){ // producerMap.put(requestId,channel); // } // //查找到这个message发送来的channel,并从这里面删除它 // public static Channel findChannel(String requestId){ // Channel channel = producerMap.remove(requestId); // return channel; // } // public static boolean pushAck(SendResult ack){ // // System.out.println("pushAck"); // return ackQueue.offer(ack); // } // public static boolean pushAck(List<SendResult> acks){ // boolean flag = false; // for(SendResult ack:acks){ // flag = ackQueue.offer(ack); // } // return flag; // } // public static SendResult getAck(){ // return ackQueue.poll(); // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/broker/SemaphoreManager.java // public class SemaphoreManager { // //每一个队列一个信号量管理里面的消费同步 // private static Map<String,Semaphore> semMap = new HashMap<String, Semaphore>(); // // //创建一个信号量 // public static void createSemaphore(String key){ // if(semMap.containsKey(key)) // return; // Semaphore semaphore = new Semaphore(0); // semMap.put(key,semaphore); // } // //信号量的值加1 // public static void increase(String key){ // semMap.get(key).release(); // } // //信号量的值减1 // public static void descrease(String key){ // try { // semMap.get(key).acquire(); // }catch (InterruptedException e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/RequestResponseFromType.java // public enum RequestResponseFromType { // Consumer, //这个消息来自消费者. // Broker, //这个消息broker. // Produce //此消息来自生产者. // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/ResponseType.java // public enum ResponseType { // SendResult, //broker回应给生产者的ACK // Message, //消息 由broker发送给消费者的消息. // AckSubscript //消费者订阅主题后,broker // } // // Path: src/main/java/com/ystruct.middleware/stormmq/model/StormResponse.java // public class StormResponse implements Serializable{ // private String requestId; //对应的回应的是哪个请求 // private Object response;// 回应的消息 // private RequestResponseFromType fromtype; //消息来自哪里 // private ResponseType responseType; //响应的类型 // // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public Object getResponse() { // return response; // } // // public void setResponse(Object response) { // this.response = response; // } // // public RequestResponseFromType getFromtype() { // return fromtype; // } // // public void setFromtype(RequestResponseFromType fromtype) { // this.fromtype = fromtype; // } // // public ResponseType getResponseType() { // return responseType; // } // // public void setResponseType(ResponseType responseType) { // this.responseType = responseType; // } // } // // Path: src/main/java/com/ystruct.middleware/stormmq/smq/SendResult.java // public class SendResult { // private String info; // private SendStatus status; // private String msgId; // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public SendStatus getStatus() { // return status; // } // // public void setStatus(SendStatus status) { // this.status = status; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // public String toString(){ // return new StringBuilder().append("msg ").append(this.msgId).append(" send ").append(this.status == SendStatus.SUCCESS ? "success":"fail").append(" info:").append(this.info).toString(); // } // // // } // Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/AckSendThread.java import broker.AckManager; import broker.SemaphoreManager; import io.netty.channel.Channel; import model.RequestResponseFromType; import model.ResponseType; import model.StormResponse; import smq.SendResult; package broker.netty; /** * Created by yang on 16-12-1. */ public class AckSendThread implements Runnable { @Override public void run() { while (true){ // System.out.println("得到一个ack"); SemaphoreManager.descrease("Ack");//获取一个ACK的信号量 // System.out.println("得到一个ack1"); //获取ack消息
SendResult ack = AckManager.getAck();
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/tool/LogWriter.java
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/Conf.java // public class Conf { // public static int connNum = 199; // public static AtomicInteger producerNum = new AtomicInteger(0); // public static Map<String/*topic*/,String> producerMap = new HashMap<String, String>(); // public static int initValue = 0; // public static void Increase(String topic){ // synchronized (producerMap){ // if(!producerMap.containsKey(topic)){ // producerNum.incrementAndGet(); // producerMap.put(topic,topic); // } // } // } // public static void Dcrease(String topic) // { // if(producerMap.containsKey(topic)) // { // producerNum.decrementAndGet(); // producerMap.remove(topic); // } // } // public static int getProducerNum() // { // return producerNum.get(); // } // }
import broker.netty.Conf; import sun.security.util.DerEncoder; import java.io.*; import java.util.Date; import java.util.Properties;
package tool; /** * Created by yang on 16-12-1. */ /** * 日志工具类,使用了单例模式,保证只有一个实例, * 为了更方便的配置日志文件名,使用属性文件配置, * 也可以在程序指定日志文件名. */ public class LogWriter { //日志的配置文件 public static final String LOG_CONFIGFILE_NAME = "/home/yang/log.properties"; //日志文件名在配置文件中的标签 public static final String LOGFILE_TAG_NAME = "logfile"; //默认的日志文件的路径和文件名称 private final String DEFAULT_LOG_FILE_NAME = "/"+System.getProperty("user.home")+"/output.log"; //该类的唯一实例 private static LogWriter logWriter; //文件的输出流 private PrintWriter write; //日志文件名 private String logFileName; private LogWriter(int version) throws Exception{ this.init(); } private LogWriter(String fileName) throws Exception{ this.logFileName = fileName; this.init(); } /** * 获取LogWriter的唯一实例 */ public synchronized static LogWriter getLogWriter() throws Exception{ if(logWriter == null){
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/Conf.java // public class Conf { // public static int connNum = 199; // public static AtomicInteger producerNum = new AtomicInteger(0); // public static Map<String/*topic*/,String> producerMap = new HashMap<String, String>(); // public static int initValue = 0; // public static void Increase(String topic){ // synchronized (producerMap){ // if(!producerMap.containsKey(topic)){ // producerNum.incrementAndGet(); // producerMap.put(topic,topic); // } // } // } // public static void Dcrease(String topic) // { // if(producerMap.containsKey(topic)) // { // producerNum.decrementAndGet(); // producerMap.remove(topic); // } // } // public static int getProducerNum() // { // return producerNum.get(); // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/tool/LogWriter.java import broker.netty.Conf; import sun.security.util.DerEncoder; import java.io.*; import java.util.Date; import java.util.Properties; package tool; /** * Created by yang on 16-12-1. */ /** * 日志工具类,使用了单例模式,保证只有一个实例, * 为了更方便的配置日志文件名,使用属性文件配置, * 也可以在程序指定日志文件名. */ public class LogWriter { //日志的配置文件 public static final String LOG_CONFIGFILE_NAME = "/home/yang/log.properties"; //日志文件名在配置文件中的标签 public static final String LOGFILE_TAG_NAME = "logfile"; //默认的日志文件的路径和文件名称 private final String DEFAULT_LOG_FILE_NAME = "/"+System.getProperty("user.home")+"/output.log"; //该类的唯一实例 private static LogWriter logWriter; //文件的输出流 private PrintWriter write; //日志文件名 private String logFileName; private LogWriter(int version) throws Exception{ this.init(); } private LogWriter(String fileName) throws Exception{ this.logFileName = fileName; this.init(); } /** * 获取LogWriter的唯一实例 */ public synchronized static LogWriter getLogWriter() throws Exception{ if(logWriter == null){
System.out.println("getLogWriter:"+Conf.initValue++);
liuhangyang/StormMQ
src/main/java/com/ystruct.middleware/stormmq/broker/netty/RecordThread.java
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/TaskManager.java // public class TaskManager { // private static ConcurrentLinkedQueue<SendTask> taskQueue = new ConcurrentLinkedQueue<SendTask>(); // //需要重新发送的队列 // private static ConcurrentLinkedQueue<SendTask> resendTaskQueue = new ConcurrentLinkedQueue<SendTask>(); // //保存重发的任务 // private static Map<String, SendTask> map = new HashMap<String, SendTask>(); // // /** // * 添加一个发送任务 // * // * @param task // */ // public static boolean pushTask(SendTask task) { // return taskQueue.offer(task); // } // // public static boolean pushTask(List<SendTask> tasks) { // boolean flag = false; // for (SendTask sendTask : tasks) { // flag = taskQueue.offer(sendTask); // } // return flag; // } // // public static SendTask getTask() { // return taskQueue.poll(); // } // // /** // * 恢复之前的发送任务 // */ // // public static void RecoverySendTask() { // if (FlushTool.log != null) { // try { // //从文件中读出未发送的任务 // List<SendTask> list = FlushTool.log.Restore(); // System.out.println("recover size: " + list.size()); // //从文件读取任务,然后增加其SendTask. // for (SendTask sendTask : list) { // pushTask(sendTask); // SemaphoreManager.increase("SendTask"); // } // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // public static boolean pushResendTask(SendTask task){ // String key = task.getGroupId()+task.getTopic()+task.getMessage().getMsgId(); // map.put(key,task); // return resendTaskQueue.offer(task); // } // public static SendTask getResendTask(){ // //出队操作 // SendTask task = resendTaskQueue.poll(); // if(task == null){ // return null; // } // String key = task.getGroupId()+task.getTopic()+task.getMessage().getMsgId(); // map.remove(key); // return task; // } // public static int getResendNumber(){ // return resendTaskQueue.size(); // } // public static boolean findInResend(String groupID,String Topic,String MsgId){ // String key = groupID + Topic + MsgId; // return map.containsKey(key); // } // }
import broker.TaskManager;
package broker.netty; /** * Created by yang on 16-12-3. */ /** * 记录发送速度的线程,同时控制重发线程的启动. */ public class RecordThread implements Runnable { private int lastSpeed = 0; private int nowSpeed = 0; @Override public void run() { while (true){ lastSpeed = ResendManager.getSendSpeek(); // System.out.println("lastSpeed:"+lastSpeed); ResendManager.record(); nowSpeed = ResendManager.getSendSpeek(); // System.out.println("nowSpeed:"+nowSpeed); //如果有重发的数据,且重发线程为0,则启动重发线程
// Path: src/main/java/com/ystruct.middleware/stormmq/broker/TaskManager.java // public class TaskManager { // private static ConcurrentLinkedQueue<SendTask> taskQueue = new ConcurrentLinkedQueue<SendTask>(); // //需要重新发送的队列 // private static ConcurrentLinkedQueue<SendTask> resendTaskQueue = new ConcurrentLinkedQueue<SendTask>(); // //保存重发的任务 // private static Map<String, SendTask> map = new HashMap<String, SendTask>(); // // /** // * 添加一个发送任务 // * // * @param task // */ // public static boolean pushTask(SendTask task) { // return taskQueue.offer(task); // } // // public static boolean pushTask(List<SendTask> tasks) { // boolean flag = false; // for (SendTask sendTask : tasks) { // flag = taskQueue.offer(sendTask); // } // return flag; // } // // public static SendTask getTask() { // return taskQueue.poll(); // } // // /** // * 恢复之前的发送任务 // */ // // public static void RecoverySendTask() { // if (FlushTool.log != null) { // try { // //从文件中读出未发送的任务 // List<SendTask> list = FlushTool.log.Restore(); // System.out.println("recover size: " + list.size()); // //从文件读取任务,然后增加其SendTask. // for (SendTask sendTask : list) { // pushTask(sendTask); // SemaphoreManager.increase("SendTask"); // } // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // public static boolean pushResendTask(SendTask task){ // String key = task.getGroupId()+task.getTopic()+task.getMessage().getMsgId(); // map.put(key,task); // return resendTaskQueue.offer(task); // } // public static SendTask getResendTask(){ // //出队操作 // SendTask task = resendTaskQueue.poll(); // if(task == null){ // return null; // } // String key = task.getGroupId()+task.getTopic()+task.getMessage().getMsgId(); // map.remove(key); // return task; // } // public static int getResendNumber(){ // return resendTaskQueue.size(); // } // public static boolean findInResend(String groupID,String Topic,String MsgId){ // String key = groupID + Topic + MsgId; // return map.containsKey(key); // } // } // Path: src/main/java/com/ystruct.middleware/stormmq/broker/netty/RecordThread.java import broker.TaskManager; package broker.netty; /** * Created by yang on 16-12-3. */ /** * 记录发送速度的线程,同时控制重发线程的启动. */ public class RecordThread implements Runnable { private int lastSpeed = 0; private int nowSpeed = 0; @Override public void run() { while (true){ lastSpeed = ResendManager.getSendSpeek(); // System.out.println("lastSpeed:"+lastSpeed); ResendManager.record(); nowSpeed = ResendManager.getSendSpeek(); // System.out.println("nowSpeed:"+nowSpeed); //如果有重发的数据,且重发线程为0,则启动重发线程
if(TaskManager.getResendNumber() > 0 && ResendManager.resendThreadNumber == 0){
cobaltdev/pipeline
src/main/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CompletionStats.java
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Contributor.java // public class Contributor { // private String username; // private int commitCount; // private Date lastCommit; // private String fullname; // private String pictureUrl; // private String profilePageUrl; // // /** // * Constructs a Contributor object. // * // * @param username Contributor's username on Bamboo // * @param commitTime Contributor's commit date // * @param fullname Contributor's full name on Jira, // * null if username not found on Jira // * @param pictureUrl Contributor's pictureUrl from Jira, // * null if username not found on Jira // * @param profilePageUrl Contributor's profilePageUrl from Jira, // * null if username not found on Jira // */ // public Contributor(String username, Date commitTime, String fullname, String pictureUrl, String profilePageUrl) { // this(username, 1, commitTime, fullname, pictureUrl, profilePageUrl); // // } // // /** // * Constructs a Contributor object. // * // * @param username Contributor's username on Bamboo // * @param commitCount Contributor's commits count // * @param commitTime Contributor's commit date // * @param fullname Contributor's full name on Jira, // * null if username not found on Jira // * @param pictureUrl Contributor's pictureUrl from Jira, // * null if username not found on Jira // * @param profilePageUrl Contributor's profilePageUrl from Jira, // * null if username not found on Jira // */ // public Contributor(String username, int commitCount, Date commitTime, String fullname, String pictureUrl, String profilePageUrl) { // this.username = username; // this.commitCount = commitCount; // this.lastCommit = commitTime; // this.fullname = fullname; // this.pictureUrl = pictureUrl; // this.profilePageUrl = profilePageUrl; // } // // /** // * Gets the username of this contributor. // * // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * Gets the number of commits of this contributor after the last deployment. // * // * @return the number of commits // */ // public int getCommitCount(){ // return commitCount; // } // // /** // * Gets the most recent commit time of this contributor. // * // * @return the date and time of last commit // */ // public Date getLastCommitTime(){ // return lastCommit; // } // // /** // * Gets the contributor's first name and last name from Bamboo if // * contributor (author) is linked to a Bamboo user. // * // * @return the user's first and last name from Bamboo. If contributor is // * not linked to a Bamboo user, username is returned. // */ // public String getFullname() { // return fullname; // } // // /** // * Gets a link to the user's profile picture on Jira. // * // * @return the url of the user's profile picture from Jira. // */ // public String getPictureUrl() { // return pictureUrl; // } // // /** // * Gets a link to the user's profile page on Jira. // * // * @return the url of the user's profile page on Jira. // */ // public String getProfilePageUrl() { // return profilePageUrl; // } // // /** // * Updates the last commit time if the given time is more recent. // * // * @param commitTime a commit time of this contributor // */ // void updateLastCommitTime(Date commitTime){ // if(commitTime.compareTo(lastCommit) > 0){ // lastCommit = commitTime; // } // } // // /** // * Increments the number of commits by 1. // */ // void incrementCommitCount(){ // commitCount++; // } // // @Override // public boolean equals(Object o){ // if (o instanceof Contributor){ // Contributor other = (Contributor) o; // if(other.username.equals(this.username)){ // return true; // } // } // return false; // } // // @Override // public int hashCode(){ // return this.username.hashCode(); // } // // }
import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.cobalt.bamboo.plugin.pipeline.cdresult.Contributor;
package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CompletionStats { private int buildNumber; private int numChanges; private Date completedDate;
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Contributor.java // public class Contributor { // private String username; // private int commitCount; // private Date lastCommit; // private String fullname; // private String pictureUrl; // private String profilePageUrl; // // /** // * Constructs a Contributor object. // * // * @param username Contributor's username on Bamboo // * @param commitTime Contributor's commit date // * @param fullname Contributor's full name on Jira, // * null if username not found on Jira // * @param pictureUrl Contributor's pictureUrl from Jira, // * null if username not found on Jira // * @param profilePageUrl Contributor's profilePageUrl from Jira, // * null if username not found on Jira // */ // public Contributor(String username, Date commitTime, String fullname, String pictureUrl, String profilePageUrl) { // this(username, 1, commitTime, fullname, pictureUrl, profilePageUrl); // // } // // /** // * Constructs a Contributor object. // * // * @param username Contributor's username on Bamboo // * @param commitCount Contributor's commits count // * @param commitTime Contributor's commit date // * @param fullname Contributor's full name on Jira, // * null if username not found on Jira // * @param pictureUrl Contributor's pictureUrl from Jira, // * null if username not found on Jira // * @param profilePageUrl Contributor's profilePageUrl from Jira, // * null if username not found on Jira // */ // public Contributor(String username, int commitCount, Date commitTime, String fullname, String pictureUrl, String profilePageUrl) { // this.username = username; // this.commitCount = commitCount; // this.lastCommit = commitTime; // this.fullname = fullname; // this.pictureUrl = pictureUrl; // this.profilePageUrl = profilePageUrl; // } // // /** // * Gets the username of this contributor. // * // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * Gets the number of commits of this contributor after the last deployment. // * // * @return the number of commits // */ // public int getCommitCount(){ // return commitCount; // } // // /** // * Gets the most recent commit time of this contributor. // * // * @return the date and time of last commit // */ // public Date getLastCommitTime(){ // return lastCommit; // } // // /** // * Gets the contributor's first name and last name from Bamboo if // * contributor (author) is linked to a Bamboo user. // * // * @return the user's first and last name from Bamboo. If contributor is // * not linked to a Bamboo user, username is returned. // */ // public String getFullname() { // return fullname; // } // // /** // * Gets a link to the user's profile picture on Jira. // * // * @return the url of the user's profile picture from Jira. // */ // public String getPictureUrl() { // return pictureUrl; // } // // /** // * Gets a link to the user's profile page on Jira. // * // * @return the url of the user's profile page on Jira. // */ // public String getProfilePageUrl() { // return profilePageUrl; // } // // /** // * Updates the last commit time if the given time is more recent. // * // * @param commitTime a commit time of this contributor // */ // void updateLastCommitTime(Date commitTime){ // if(commitTime.compareTo(lastCommit) > 0){ // lastCommit = commitTime; // } // } // // /** // * Increments the number of commits by 1. // */ // void incrementCommitCount(){ // commitCount++; // } // // @Override // public boolean equals(Object o){ // if (o instanceof Contributor){ // Contributor other = (Contributor) o; // if(other.username.equals(this.username)){ // return true; // } // } // return false; // } // // @Override // public int hashCode(){ // return this.username.hashCode(); // } // // } // Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CompletionStats.java import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.cobalt.bamboo.plugin.pipeline.cdresult.Contributor; package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CompletionStats { private int buildNumber; private int numChanges; private Date completedDate;
private Map<String, Contributor> contributors;
cobaltdev/pipeline
src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CDPerformanceFactoryTest.java
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/ContributorBuilder.java // public class ContributorBuilder { // private static final String JIRA_USER_AVATAR_PATH = "/secure/useravatar?ownerId="; // private static final String JIRA_PROFILE_PATH = "/secure/ViewProfile.jspa?name="; // // private String jiraBaseUrl; // // /** // * Constructs a ContributorBuilder object. // * // * @param jiraApplinksService to connect to Jira via Application Link. // */ // public ContributorBuilder(JiraApplinksService jiraApplinksService){ // // User need to make sure they put the JIRA applink as the primary application link to Jira // if(jiraApplinksService == null){ // throw new IllegalArgumentException("Arguments can't be null."); // } // jiraBaseUrl = null; // // Iterable<ApplicationLink> appLinkService = jiraApplinksService.getJiraApplicationLinks(); // if (appLinkService != null || appLinkService.iterator() != null) { // Iterator<ApplicationLink> appLinks = jiraApplinksService.getJiraApplicationLinks().iterator(); // if (appLinks.hasNext()) { // jiraBaseUrl = appLinks.next().getRpcUrl().toString(); // } // } // // } // // /** // * Create a Contributor based on the username, last commit date, and full name. // * ContributorBuilder will construct the picture url and profile page url using // * jiraBaseUrl given by the application link. // * // * @param username of the contributor // * @param lastCommitDate of the contributor // * @param fullName of the contributor from Bamboo // * @return the Contributor created. If there are application link to Jira, // * Contributor's picture url and profile page url will be set accordingly, // * otherwise, those fields will be null. // */ // public Contributor createContributor(String username, Date lastCommitDate, String fullName){ // if (jiraBaseUrl != null) { // String pictureUrl = jiraBaseUrl + JIRA_USER_AVATAR_PATH + username; // String profilePageUrl = jiraBaseUrl + JIRA_PROFILE_PATH + username; // return new Contributor(username, lastCommitDate, fullName, pictureUrl, profilePageUrl); // } else { // return new Contributor(username, lastCommitDate, fullName, null, null); // } // } // }
import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.*; import com.atlassian.applinks.api.ApplicationLink; import com.atlassian.bamboo.applinks.JiraApplinksService; import com.atlassian.bamboo.author.Author; import com.atlassian.bamboo.chains.ChainResultsSummary; import com.atlassian.bamboo.commit.Commit; import com.atlassian.bamboo.resultsummary.ResultsSummary; import com.cobalt.bamboo.plugin.pipeline.cdresult.ContributorBuilder; import com.google.common.collect.ImmutableList;
package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CDPerformanceFactoryTest { private Date day1; private Date day2; private Date day3; private Date day4; private Date day5; private Date current;
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/ContributorBuilder.java // public class ContributorBuilder { // private static final String JIRA_USER_AVATAR_PATH = "/secure/useravatar?ownerId="; // private static final String JIRA_PROFILE_PATH = "/secure/ViewProfile.jspa?name="; // // private String jiraBaseUrl; // // /** // * Constructs a ContributorBuilder object. // * // * @param jiraApplinksService to connect to Jira via Application Link. // */ // public ContributorBuilder(JiraApplinksService jiraApplinksService){ // // User need to make sure they put the JIRA applink as the primary application link to Jira // if(jiraApplinksService == null){ // throw new IllegalArgumentException("Arguments can't be null."); // } // jiraBaseUrl = null; // // Iterable<ApplicationLink> appLinkService = jiraApplinksService.getJiraApplicationLinks(); // if (appLinkService != null || appLinkService.iterator() != null) { // Iterator<ApplicationLink> appLinks = jiraApplinksService.getJiraApplicationLinks().iterator(); // if (appLinks.hasNext()) { // jiraBaseUrl = appLinks.next().getRpcUrl().toString(); // } // } // // } // // /** // * Create a Contributor based on the username, last commit date, and full name. // * ContributorBuilder will construct the picture url and profile page url using // * jiraBaseUrl given by the application link. // * // * @param username of the contributor // * @param lastCommitDate of the contributor // * @param fullName of the contributor from Bamboo // * @return the Contributor created. If there are application link to Jira, // * Contributor's picture url and profile page url will be set accordingly, // * otherwise, those fields will be null. // */ // public Contributor createContributor(String username, Date lastCommitDate, String fullName){ // if (jiraBaseUrl != null) { // String pictureUrl = jiraBaseUrl + JIRA_USER_AVATAR_PATH + username; // String profilePageUrl = jiraBaseUrl + JIRA_PROFILE_PATH + username; // return new Contributor(username, lastCommitDate, fullName, pictureUrl, profilePageUrl); // } else { // return new Contributor(username, lastCommitDate, fullName, null, null); // } // } // } // Path: src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CDPerformanceFactoryTest.java import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.*; import com.atlassian.applinks.api.ApplicationLink; import com.atlassian.bamboo.applinks.JiraApplinksService; import com.atlassian.bamboo.author.Author; import com.atlassian.bamboo.chains.ChainResultsSummary; import com.atlassian.bamboo.commit.Commit; import com.atlassian.bamboo.resultsummary.ResultsSummary; import com.cobalt.bamboo.plugin.pipeline.cdresult.ContributorBuilder; import com.google.common.collect.ImmutableList; package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CDPerformanceFactoryTest { private Date day1; private Date day2; private Date day3; private Date day4; private Date day5; private Date current;
ContributorBuilder cb;
cobaltdev/pipeline
src/main/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/UptimeGrade.java
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Build.java // public class Build { // private ChainResultsSummary buildResult; // private ProgressBar progressBar; // // /** // * Constructs a Build object // * // * @param buildResult from Bamboo to construct off of // * @param progressBar for builds that are currently building // */ // public Build(ChainResultsSummary buildResult, ProgressBar progressBar){ // this.buildResult = buildResult; // this.progressBar = progressBar; // } // // /** // * Returns the build key of this build. // * Returns null when there are no build yet. // * // * @return build key // */ // public String getBuildKey() { // if (buildResult == null) { // return null; // } else { // return buildResult.getBuildResultKey(); // } // } // // /** // * Returns the build number of this build. // * Returns -1 when there are no build yet. // * // * @return build number // */ // public int getBuildNumber() { // if (buildResult == null) { // return -1; // } else { // return buildResult.getBuildNumber(); // } // } // // /** // * Get the CDPipelineState based on the state of buildResult, but only // * includes the states that are to the interest of our users, of this pipeline stage. // * // * @return the CDPipelineState, which can be CD_SUCCESS, CD_FAILED, CD_IN_PROGRESS, // * CD_NOT_BUILT, CD_MANUALLY_PAUSED // */ // public CDPipelineState getCDPipelineState() { // if (buildResult == null) { // return CDPipelineState.CD_NOT_BUILT; // } else { // if (buildResult.isSuccessful()) { // if (buildResult.isContinuable()) { // return CDPipelineState.CD_MANUALLY_PAUSED; // } else { // return CDPipelineState.CD_SUCCESS; // } // } else if (buildResult.isFailed()) { // return CDPipelineState.CD_FAILED; // } else if (buildResult.isInProgress() || getPercentageCompleted() > 0) { // return CDPipelineState.CD_IN_PROGRESS; // } else if (buildResult.isQueued()) { // return CDPipelineState.CD_QUEUED; // } else { // return CDPipelineState.CD_NOT_BUILT; // } // } // } // // /** // * Get the percentage completed if this Build is currently building. // * // * @return percentage completed in double format if this Build is currently building, // * -1 otherwise. // */ // public double getPercentageCompleted() { // if (progressBar != null) { // return progressBar.getPercentageCompleted(); // } // return -1; // } // // /** // * Get the time remaining if this Build is currently building. // * // * @return time remaining in pretty string format if this Build is currently building, // * null otherwise. // */ // public String getTimeRemaining() { // if (progressBar != null) { // return progressBar.getPrettyTimeRemaining(false); // } // return null; // } // // /** // * Get the completed date of this build. // * // * @return the completed Date of this build. // */ // public Date getBuildCompletedDate() { // if(buildResult == null){ // return null; // } // return buildResult.getBuildCompletedDate(); // } // // /** // * Return whether this build is successful. // * // * @return true if this build is successful, false otherwise. // */ // public boolean isSuccessful() { // if(buildResult == null){ // return false; // } // return buildResult.isSuccessful(); // } // }
import java.util.Date; import com.cobalt.bamboo.plugin.pipeline.cdresult.Build;
Date current = new Date(); long totalUptimeToCurrent = this.totalUptime; if(currentBuildSuccess){ totalUptimeToCurrent += current.getTime() - currentBuildDate.getTime(); } return totalUptimeToCurrent * 1.0 / (current.getTime() - startDate.getTime()); } /** * Get the grade based on the uptime percentage * Return null if there's no complted build. * @return the grade based on the uptime percentage */ public String getGrade(){ double uptimePercentage = getUptimePercentage(); if(uptimePercentage < 0){ return null; } for(int i = 0; i < GRADE_SCALE.length; i++){ if(uptimePercentage >= GRADE_SCALE[i]){ return LETTER_GRADE[i]; } } return LETTER_GRADE[LETTER_GRADE.length - 1]; } /** * Update with the most recent build. * @param newBuild to update in order to calculate the uptime percentage */
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Build.java // public class Build { // private ChainResultsSummary buildResult; // private ProgressBar progressBar; // // /** // * Constructs a Build object // * // * @param buildResult from Bamboo to construct off of // * @param progressBar for builds that are currently building // */ // public Build(ChainResultsSummary buildResult, ProgressBar progressBar){ // this.buildResult = buildResult; // this.progressBar = progressBar; // } // // /** // * Returns the build key of this build. // * Returns null when there are no build yet. // * // * @return build key // */ // public String getBuildKey() { // if (buildResult == null) { // return null; // } else { // return buildResult.getBuildResultKey(); // } // } // // /** // * Returns the build number of this build. // * Returns -1 when there are no build yet. // * // * @return build number // */ // public int getBuildNumber() { // if (buildResult == null) { // return -1; // } else { // return buildResult.getBuildNumber(); // } // } // // /** // * Get the CDPipelineState based on the state of buildResult, but only // * includes the states that are to the interest of our users, of this pipeline stage. // * // * @return the CDPipelineState, which can be CD_SUCCESS, CD_FAILED, CD_IN_PROGRESS, // * CD_NOT_BUILT, CD_MANUALLY_PAUSED // */ // public CDPipelineState getCDPipelineState() { // if (buildResult == null) { // return CDPipelineState.CD_NOT_BUILT; // } else { // if (buildResult.isSuccessful()) { // if (buildResult.isContinuable()) { // return CDPipelineState.CD_MANUALLY_PAUSED; // } else { // return CDPipelineState.CD_SUCCESS; // } // } else if (buildResult.isFailed()) { // return CDPipelineState.CD_FAILED; // } else if (buildResult.isInProgress() || getPercentageCompleted() > 0) { // return CDPipelineState.CD_IN_PROGRESS; // } else if (buildResult.isQueued()) { // return CDPipelineState.CD_QUEUED; // } else { // return CDPipelineState.CD_NOT_BUILT; // } // } // } // // /** // * Get the percentage completed if this Build is currently building. // * // * @return percentage completed in double format if this Build is currently building, // * -1 otherwise. // */ // public double getPercentageCompleted() { // if (progressBar != null) { // return progressBar.getPercentageCompleted(); // } // return -1; // } // // /** // * Get the time remaining if this Build is currently building. // * // * @return time remaining in pretty string format if this Build is currently building, // * null otherwise. // */ // public String getTimeRemaining() { // if (progressBar != null) { // return progressBar.getPrettyTimeRemaining(false); // } // return null; // } // // /** // * Get the completed date of this build. // * // * @return the completed Date of this build. // */ // public Date getBuildCompletedDate() { // if(buildResult == null){ // return null; // } // return buildResult.getBuildCompletedDate(); // } // // /** // * Return whether this build is successful. // * // * @return true if this build is successful, false otherwise. // */ // public boolean isSuccessful() { // if(buildResult == null){ // return false; // } // return buildResult.isSuccessful(); // } // } // Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/UptimeGrade.java import java.util.Date; import com.cobalt.bamboo.plugin.pipeline.cdresult.Build; Date current = new Date(); long totalUptimeToCurrent = this.totalUptime; if(currentBuildSuccess){ totalUptimeToCurrent += current.getTime() - currentBuildDate.getTime(); } return totalUptimeToCurrent * 1.0 / (current.getTime() - startDate.getTime()); } /** * Get the grade based on the uptime percentage * Return null if there's no complted build. * @return the grade based on the uptime percentage */ public String getGrade(){ double uptimePercentage = getUptimePercentage(); if(uptimePercentage < 0){ return null; } for(int i = 0; i < GRADE_SCALE.length; i++){ if(uptimePercentage >= GRADE_SCALE[i]){ return LETTER_GRADE[i]; } } return LETTER_GRADE[LETTER_GRADE.length - 1]; } /** * Update with the most recent build. * @param newBuild to update in order to calculate the uptime percentage */
public void update(Build newBuild) {
cobaltdev/pipeline
src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/UptimeGradeTest.java
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Build.java // public class Build { // private ChainResultsSummary buildResult; // private ProgressBar progressBar; // // /** // * Constructs a Build object // * // * @param buildResult from Bamboo to construct off of // * @param progressBar for builds that are currently building // */ // public Build(ChainResultsSummary buildResult, ProgressBar progressBar){ // this.buildResult = buildResult; // this.progressBar = progressBar; // } // // /** // * Returns the build key of this build. // * Returns null when there are no build yet. // * // * @return build key // */ // public String getBuildKey() { // if (buildResult == null) { // return null; // } else { // return buildResult.getBuildResultKey(); // } // } // // /** // * Returns the build number of this build. // * Returns -1 when there are no build yet. // * // * @return build number // */ // public int getBuildNumber() { // if (buildResult == null) { // return -1; // } else { // return buildResult.getBuildNumber(); // } // } // // /** // * Get the CDPipelineState based on the state of buildResult, but only // * includes the states that are to the interest of our users, of this pipeline stage. // * // * @return the CDPipelineState, which can be CD_SUCCESS, CD_FAILED, CD_IN_PROGRESS, // * CD_NOT_BUILT, CD_MANUALLY_PAUSED // */ // public CDPipelineState getCDPipelineState() { // if (buildResult == null) { // return CDPipelineState.CD_NOT_BUILT; // } else { // if (buildResult.isSuccessful()) { // if (buildResult.isContinuable()) { // return CDPipelineState.CD_MANUALLY_PAUSED; // } else { // return CDPipelineState.CD_SUCCESS; // } // } else if (buildResult.isFailed()) { // return CDPipelineState.CD_FAILED; // } else if (buildResult.isInProgress() || getPercentageCompleted() > 0) { // return CDPipelineState.CD_IN_PROGRESS; // } else if (buildResult.isQueued()) { // return CDPipelineState.CD_QUEUED; // } else { // return CDPipelineState.CD_NOT_BUILT; // } // } // } // // /** // * Get the percentage completed if this Build is currently building. // * // * @return percentage completed in double format if this Build is currently building, // * -1 otherwise. // */ // public double getPercentageCompleted() { // if (progressBar != null) { // return progressBar.getPercentageCompleted(); // } // return -1; // } // // /** // * Get the time remaining if this Build is currently building. // * // * @return time remaining in pretty string format if this Build is currently building, // * null otherwise. // */ // public String getTimeRemaining() { // if (progressBar != null) { // return progressBar.getPrettyTimeRemaining(false); // } // return null; // } // // /** // * Get the completed date of this build. // * // * @return the completed Date of this build. // */ // public Date getBuildCompletedDate() { // if(buildResult == null){ // return null; // } // return buildResult.getBuildCompletedDate(); // } // // /** // * Return whether this build is successful. // * // * @return true if this build is successful, false otherwise. // */ // public boolean isSuccessful() { // if(buildResult == null){ // return false; // } // return buildResult.isSuccessful(); // } // }
import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Date; import org.junit.Test; import com.cobalt.bamboo.plugin.pipeline.cdresult.Build;
Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 0, false, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "F", g.getGrade()); } @Test public void testWithTotalUpTimeSuccess() { Date current = new Date(); Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 50000, true, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0.75, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "C", g.getGrade()); } @Test public void testWithTotalUpTimeFail() { Date current = new Date(); Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 50000, false, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0.25, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "F", g.getGrade()); } @Test public void testUpdateNoStartGradeWithIncompletedBuild() { UptimeGrade g = new UptimeGrade(null, 0, false, null);
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/Build.java // public class Build { // private ChainResultsSummary buildResult; // private ProgressBar progressBar; // // /** // * Constructs a Build object // * // * @param buildResult from Bamboo to construct off of // * @param progressBar for builds that are currently building // */ // public Build(ChainResultsSummary buildResult, ProgressBar progressBar){ // this.buildResult = buildResult; // this.progressBar = progressBar; // } // // /** // * Returns the build key of this build. // * Returns null when there are no build yet. // * // * @return build key // */ // public String getBuildKey() { // if (buildResult == null) { // return null; // } else { // return buildResult.getBuildResultKey(); // } // } // // /** // * Returns the build number of this build. // * Returns -1 when there are no build yet. // * // * @return build number // */ // public int getBuildNumber() { // if (buildResult == null) { // return -1; // } else { // return buildResult.getBuildNumber(); // } // } // // /** // * Get the CDPipelineState based on the state of buildResult, but only // * includes the states that are to the interest of our users, of this pipeline stage. // * // * @return the CDPipelineState, which can be CD_SUCCESS, CD_FAILED, CD_IN_PROGRESS, // * CD_NOT_BUILT, CD_MANUALLY_PAUSED // */ // public CDPipelineState getCDPipelineState() { // if (buildResult == null) { // return CDPipelineState.CD_NOT_BUILT; // } else { // if (buildResult.isSuccessful()) { // if (buildResult.isContinuable()) { // return CDPipelineState.CD_MANUALLY_PAUSED; // } else { // return CDPipelineState.CD_SUCCESS; // } // } else if (buildResult.isFailed()) { // return CDPipelineState.CD_FAILED; // } else if (buildResult.isInProgress() || getPercentageCompleted() > 0) { // return CDPipelineState.CD_IN_PROGRESS; // } else if (buildResult.isQueued()) { // return CDPipelineState.CD_QUEUED; // } else { // return CDPipelineState.CD_NOT_BUILT; // } // } // } // // /** // * Get the percentage completed if this Build is currently building. // * // * @return percentage completed in double format if this Build is currently building, // * -1 otherwise. // */ // public double getPercentageCompleted() { // if (progressBar != null) { // return progressBar.getPercentageCompleted(); // } // return -1; // } // // /** // * Get the time remaining if this Build is currently building. // * // * @return time remaining in pretty string format if this Build is currently building, // * null otherwise. // */ // public String getTimeRemaining() { // if (progressBar != null) { // return progressBar.getPrettyTimeRemaining(false); // } // return null; // } // // /** // * Get the completed date of this build. // * // * @return the completed Date of this build. // */ // public Date getBuildCompletedDate() { // if(buildResult == null){ // return null; // } // return buildResult.getBuildCompletedDate(); // } // // /** // * Return whether this build is successful. // * // * @return true if this build is successful, false otherwise. // */ // public boolean isSuccessful() { // if(buildResult == null){ // return false; // } // return buildResult.isSuccessful(); // } // } // Path: src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/UptimeGradeTest.java import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Date; import org.junit.Test; import com.cobalt.bamboo.plugin.pipeline.cdresult.Build; Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 0, false, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "F", g.getGrade()); } @Test public void testWithTotalUpTimeSuccess() { Date current = new Date(); Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 50000, true, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0.75, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "C", g.getGrade()); } @Test public void testWithTotalUpTimeFail() { Date current = new Date(); Date currentBuildDate = new Date(current.getTime() - 100000); Date startDate = new Date(current.getTime() - 200000); UptimeGrade g = new UptimeGrade(startDate, 50000, false, currentBuildDate); assertEquals("Uptime percentage is not as expected.", 0.25, g.getUptimePercentage(), 0.0001); assertEquals("Grade is not as expected.", "F", g.getGrade()); } @Test public void testUpdateNoStartGradeWithIncompletedBuild() { UptimeGrade g = new UptimeGrade(null, 0, false, null);
Build build = mock(Build.class);
cobaltdev/pipeline
src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CDPerformanceAddAuthorsTest.java
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/ContributorBuilder.java // public class ContributorBuilder { // private static final String JIRA_USER_AVATAR_PATH = "/secure/useravatar?ownerId="; // private static final String JIRA_PROFILE_PATH = "/secure/ViewProfile.jspa?name="; // // private String jiraBaseUrl; // // /** // * Constructs a ContributorBuilder object. // * // * @param jiraApplinksService to connect to Jira via Application Link. // */ // public ContributorBuilder(JiraApplinksService jiraApplinksService){ // // User need to make sure they put the JIRA applink as the primary application link to Jira // if(jiraApplinksService == null){ // throw new IllegalArgumentException("Arguments can't be null."); // } // jiraBaseUrl = null; // // Iterable<ApplicationLink> appLinkService = jiraApplinksService.getJiraApplicationLinks(); // if (appLinkService != null || appLinkService.iterator() != null) { // Iterator<ApplicationLink> appLinks = jiraApplinksService.getJiraApplicationLinks().iterator(); // if (appLinks.hasNext()) { // jiraBaseUrl = appLinks.next().getRpcUrl().toString(); // } // } // // } // // /** // * Create a Contributor based on the username, last commit date, and full name. // * ContributorBuilder will construct the picture url and profile page url using // * jiraBaseUrl given by the application link. // * // * @param username of the contributor // * @param lastCommitDate of the contributor // * @param fullName of the contributor from Bamboo // * @return the Contributor created. If there are application link to Jira, // * Contributor's picture url and profile page url will be set accordingly, // * otherwise, those fields will be null. // */ // public Contributor createContributor(String username, Date lastCommitDate, String fullName){ // if (jiraBaseUrl != null) { // String pictureUrl = jiraBaseUrl + JIRA_USER_AVATAR_PATH + username; // String profilePageUrl = jiraBaseUrl + JIRA_PROFILE_PATH + username; // return new Contributor(username, lastCommitDate, fullName, pictureUrl, profilePageUrl); // } else { // return new Contributor(username, lastCommitDate, fullName, null, null); // } // } // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Test; import com.atlassian.applinks.api.ApplicationLink; import com.atlassian.bamboo.applinks.JiraApplinksService; import com.atlassian.bamboo.author.Author; import com.atlassian.bamboo.commit.Commit; import com.cobalt.bamboo.plugin.pipeline.cdresult.ContributorBuilder;
package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CDPerformanceAddAuthorsTest { private static final int COMMIT_LIST_SIZE = 10; // >= 3 CompletionStats stat;
// Path: src/main/java/com/cobalt/bamboo/plugin/pipeline/cdresult/ContributorBuilder.java // public class ContributorBuilder { // private static final String JIRA_USER_AVATAR_PATH = "/secure/useravatar?ownerId="; // private static final String JIRA_PROFILE_PATH = "/secure/ViewProfile.jspa?name="; // // private String jiraBaseUrl; // // /** // * Constructs a ContributorBuilder object. // * // * @param jiraApplinksService to connect to Jira via Application Link. // */ // public ContributorBuilder(JiraApplinksService jiraApplinksService){ // // User need to make sure they put the JIRA applink as the primary application link to Jira // if(jiraApplinksService == null){ // throw new IllegalArgumentException("Arguments can't be null."); // } // jiraBaseUrl = null; // // Iterable<ApplicationLink> appLinkService = jiraApplinksService.getJiraApplicationLinks(); // if (appLinkService != null || appLinkService.iterator() != null) { // Iterator<ApplicationLink> appLinks = jiraApplinksService.getJiraApplicationLinks().iterator(); // if (appLinks.hasNext()) { // jiraBaseUrl = appLinks.next().getRpcUrl().toString(); // } // } // // } // // /** // * Create a Contributor based on the username, last commit date, and full name. // * ContributorBuilder will construct the picture url and profile page url using // * jiraBaseUrl given by the application link. // * // * @param username of the contributor // * @param lastCommitDate of the contributor // * @param fullName of the contributor from Bamboo // * @return the Contributor created. If there are application link to Jira, // * Contributor's picture url and profile page url will be set accordingly, // * otherwise, those fields will be null. // */ // public Contributor createContributor(String username, Date lastCommitDate, String fullName){ // if (jiraBaseUrl != null) { // String pictureUrl = jiraBaseUrl + JIRA_USER_AVATAR_PATH + username; // String profilePageUrl = jiraBaseUrl + JIRA_PROFILE_PATH + username; // return new Contributor(username, lastCommitDate, fullName, pictureUrl, profilePageUrl); // } else { // return new Contributor(username, lastCommitDate, fullName, null, null); // } // } // } // Path: src/test/java/com/cobalt/bamboo/plugin/pipeline/cdperformance/CDPerformanceAddAuthorsTest.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Test; import com.atlassian.applinks.api.ApplicationLink; import com.atlassian.bamboo.applinks.JiraApplinksService; import com.atlassian.bamboo.author.Author; import com.atlassian.bamboo.commit.Commit; import com.cobalt.bamboo.plugin.pipeline.cdresult.ContributorBuilder; package com.cobalt.bamboo.plugin.pipeline.cdperformance; public class CDPerformanceAddAuthorsTest { private static final int COMMIT_LIST_SIZE = 10; // >= 3 CompletionStats stat;
ContributorBuilder cb;
motech/MOTECH-WS-API
src/main/java/org/motechproject/ws/Patient.java
// Path: src/main/java/org/motechproject/ws/rct/PregnancyTrimester.java // public enum PregnancyTrimester { // NONE, FIRST , SECOND , THIRD // }
import org.motechproject.ws.rct.PregnancyTrimester; import java.util.Date;
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.motechproject.ws; public class Patient { String motechId; String preferredName; String firstName; String lastName; Date birthDate; Integer age; Gender sex; String community; String phoneNumber; Date estimateDueDate; Date deliveryDate; Care[] cares; ContactNumberType contactNumberType;
// Path: src/main/java/org/motechproject/ws/rct/PregnancyTrimester.java // public enum PregnancyTrimester { // NONE, FIRST , SECOND , THIRD // } // Path: src/main/java/org/motechproject/ws/Patient.java import org.motechproject.ws.rct.PregnancyTrimester; import java.util.Date; /** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.motechproject.ws; public class Patient { String motechId; String preferredName; String firstName; String lastName; Date birthDate; Integer age; Gender sex; String community; String phoneNumber; Date estimateDueDate; Date deliveryDate; Care[] cares; ContactNumberType contactNumberType;
PregnancyTrimester pregnancyTrimester;
motech/MOTECH-WS-API
src/test/java/org/motechproject/ws/PatientTest.java
// Path: src/main/java/org/motechproject/ws/rct/PregnancyTrimester.java // public enum PregnancyTrimester { // NONE, FIRST , SECOND , THIRD // }
import org.junit.Test; import org.motechproject.ws.rct.PregnancyTrimester; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package org.motechproject.ws; public class PatientTest { @Test public void shouldDetermineIfPatientHasRegisteredPregnancy(){ Patient patient = new Patient(); assertFalse(patient.isPregnancyRegistered()); Patient pregnantPatient = new Patient(); pregnantPatient.setEstimateDueDate(new Date()); assertTrue(pregnantPatient.isPregnancyRegistered()); } @Test public void shouldDetermineTrimesterAsSecond(){ Patient patient = new Patient(); Calendar instance = Calendar.getInstance(); instance.add(Calendar.MONTH,5); patient.setEstimateDueDate(instance.getTime()); assertTrue(patient.isPregnancyRegistered());
// Path: src/main/java/org/motechproject/ws/rct/PregnancyTrimester.java // public enum PregnancyTrimester { // NONE, FIRST , SECOND , THIRD // } // Path: src/test/java/org/motechproject/ws/PatientTest.java import org.junit.Test; import org.motechproject.ws.rct.PregnancyTrimester; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package org.motechproject.ws; public class PatientTest { @Test public void shouldDetermineIfPatientHasRegisteredPregnancy(){ Patient patient = new Patient(); assertFalse(patient.isPregnancyRegistered()); Patient pregnantPatient = new Patient(); pregnantPatient.setEstimateDueDate(new Date()); assertTrue(pregnantPatient.isPregnancyRegistered()); } @Test public void shouldDetermineTrimesterAsSecond(){ Patient patient = new Patient(); Calendar instance = Calendar.getInstance(); instance.add(Calendar.MONTH,5); patient.setEstimateDueDate(instance.getTime()); assertTrue(patient.isPregnancyRegistered());
assertTrue(PregnancyTrimester.SECOND.equals(patient.pregnancyTrimester()));
motech/MOTECH-WS-API
src/main/java/org/motechproject/ws/server/RegistrarService.java
// Path: src/main/java/org/motechproject/ws/rct/RCTRegistrationConfirmation.java // public class RCTRegistrationConfirmation { // // private String text; // // private Boolean errors; // // public RCTRegistrationConfirmation() { // // } // // public RCTRegistrationConfirmation(String text, Boolean errors){ // this.text = text; // this.errors = errors; // } // // @Override // public String toString() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getText(){ // return text; // } // // public Boolean getErrors() { // return errors; // } // // public void setErrors(Boolean errors) { // this.errors = errors; // } // }
import org.motechproject.ws.*; import org.motechproject.ws.rct.RCTRegistrationConfirmation; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import java.util.Date;
@WebParam(name = "facilityId") Integer facilityId, @WebParam(name = "firstName") String firstName, @WebParam(name = "lastName") String lastName, @WebParam(name = "preferredName") String preferredName, @WebParam(name = "birthDate") Date birthDate, @WebParam(name = "nhis") String nhis, @WebParam(name = "phoneNumber") String phoneNumber) throws ValidationException; @WebMethod public Patient queryPatient(@WebParam(name = "staffId") Integer staffId, @WebParam(name = "facilityId") Integer facilityId, @WebParam(name = "motechId") Integer motechId) throws ValidationException; @WebMethod public String[] getPatientEnrollments( @WebParam(name = "motechId") Integer motechId) throws ValidationException; @WebMethod public void log(@WebParam(name = "type") LogType type, @WebParam(name = "message") String message); @WebMethod public void setMessageStatus( @WebParam(name = "messageId") String messageId, @WebParam(name = "success") Boolean success); @WebMethod
// Path: src/main/java/org/motechproject/ws/rct/RCTRegistrationConfirmation.java // public class RCTRegistrationConfirmation { // // private String text; // // private Boolean errors; // // public RCTRegistrationConfirmation() { // // } // // public RCTRegistrationConfirmation(String text, Boolean errors){ // this.text = text; // this.errors = errors; // } // // @Override // public String toString() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getText(){ // return text; // } // // public Boolean getErrors() { // return errors; // } // // public void setErrors(Boolean errors) { // this.errors = errors; // } // } // Path: src/main/java/org/motechproject/ws/server/RegistrarService.java import org.motechproject.ws.*; import org.motechproject.ws.rct.RCTRegistrationConfirmation; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import java.util.Date; @WebParam(name = "facilityId") Integer facilityId, @WebParam(name = "firstName") String firstName, @WebParam(name = "lastName") String lastName, @WebParam(name = "preferredName") String preferredName, @WebParam(name = "birthDate") Date birthDate, @WebParam(name = "nhis") String nhis, @WebParam(name = "phoneNumber") String phoneNumber) throws ValidationException; @WebMethod public Patient queryPatient(@WebParam(name = "staffId") Integer staffId, @WebParam(name = "facilityId") Integer facilityId, @WebParam(name = "motechId") Integer motechId) throws ValidationException; @WebMethod public String[] getPatientEnrollments( @WebParam(name = "motechId") Integer motechId) throws ValidationException; @WebMethod public void log(@WebParam(name = "type") LogType type, @WebParam(name = "message") String message); @WebMethod public void setMessageStatus( @WebParam(name = "messageId") String messageId, @WebParam(name = "success") Boolean success); @WebMethod
public RCTRegistrationConfirmation registerForRCT(@WebParam(name = "staffId") Integer staffId,
cjh1/gerrit
gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/account/GroupAdminServiceImpl.java
// Path: gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java // public interface GroupCache { // public AccountGroup get(AccountGroup.Id groupId); // // public AccountGroup get(AccountGroup.NameKey name); // // public AccountGroup get(AccountGroup.UUID uuid); // // public Collection<AccountGroup> get(AccountGroup.ExternalNameKey externalName); // // public void evict(AccountGroup group); // // public void evictAfterRename(AccountGroup.NameKey oldName); // }
import com.google.gerrit.common.data.GroupAdminService; import com.google.gerrit.common.data.GroupDetail; import com.google.gerrit.common.data.GroupList; import com.google.gerrit.common.data.GroupOptions; import com.google.gerrit.common.errors.InactiveAccountException; import com.google.gerrit.common.errors.NameAlreadyUsedException; import com.google.gerrit.common.errors.NoSuchAccountException; import com.google.gerrit.common.errors.NoSuchEntityException; import com.google.gerrit.common.errors.NoSuchGroupException; import com.google.gerrit.httpd.rpc.BaseServiceImplementation; import com.google.gerrit.reviewdb.Account; import com.google.gerrit.reviewdb.AccountGroup; import com.google.gerrit.reviewdb.AccountGroupInclude; import com.google.gerrit.reviewdb.AccountGroupIncludeAudit; import com.google.gerrit.reviewdb.AccountGroupMember; import com.google.gerrit.reviewdb.AccountGroupMemberAudit; import com.google.gerrit.reviewdb.ReviewDb; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountResolver; import com.google.gerrit.server.account.GroupCache; import com.google.gerrit.server.account.GroupControl; import com.google.gerrit.server.account.GroupIncludeCache; import com.google.gerrit.server.account.Realm; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwtjsonrpc.client.VoidResult; import com.google.gwtorm.client.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set;
// Copyright (C) 2008 The Android Open Source Project // // 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 com.google.gerrit.httpd.rpc.account; class GroupAdminServiceImpl extends BaseServiceImplementation implements GroupAdminService { private final Provider<IdentifiedUser> identifiedUser; private final AccountCache accountCache; private final AccountResolver accountResolver; private final Realm accountRealm;
// Path: gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java // public interface GroupCache { // public AccountGroup get(AccountGroup.Id groupId); // // public AccountGroup get(AccountGroup.NameKey name); // // public AccountGroup get(AccountGroup.UUID uuid); // // public Collection<AccountGroup> get(AccountGroup.ExternalNameKey externalName); // // public void evict(AccountGroup group); // // public void evictAfterRename(AccountGroup.NameKey oldName); // } // Path: gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/account/GroupAdminServiceImpl.java import com.google.gerrit.common.data.GroupAdminService; import com.google.gerrit.common.data.GroupDetail; import com.google.gerrit.common.data.GroupList; import com.google.gerrit.common.data.GroupOptions; import com.google.gerrit.common.errors.InactiveAccountException; import com.google.gerrit.common.errors.NameAlreadyUsedException; import com.google.gerrit.common.errors.NoSuchAccountException; import com.google.gerrit.common.errors.NoSuchEntityException; import com.google.gerrit.common.errors.NoSuchGroupException; import com.google.gerrit.httpd.rpc.BaseServiceImplementation; import com.google.gerrit.reviewdb.Account; import com.google.gerrit.reviewdb.AccountGroup; import com.google.gerrit.reviewdb.AccountGroupInclude; import com.google.gerrit.reviewdb.AccountGroupIncludeAudit; import com.google.gerrit.reviewdb.AccountGroupMember; import com.google.gerrit.reviewdb.AccountGroupMemberAudit; import com.google.gerrit.reviewdb.ReviewDb; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountResolver; import com.google.gerrit.server.account.GroupCache; import com.google.gerrit.server.account.GroupControl; import com.google.gerrit.server.account.GroupIncludeCache; import com.google.gerrit.server.account.Realm; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwtjsonrpc.client.VoidResult; import com.google.gwtorm.client.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; // Copyright (C) 2008 The Android Open Source Project // // 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 com.google.gerrit.httpd.rpc.account; class GroupAdminServiceImpl extends BaseServiceImplementation implements GroupAdminService { private final Provider<IdentifiedUser> identifiedUser; private final AccountCache accountCache; private final AccountResolver accountResolver; private final Realm accountRealm;
private final GroupCache groupCache;
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */
public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
directoryEntries.release(newEntry); accessData().unlockHierarchyChanges(); directoryLock.writeLock().unlock(); } public boolean isEmptyDirectory() { int count = 0; directoryLock.readLock().lock(); for (@SuppressWarnings("unused") DirectoryEntry dir : iterateDirectory()) { count += 1; if (count >= 3) { directoryLock.readLock().unlock(); return false; } } directoryLock.readLock().unlock(); return true; } /** * Lookup name in directory. This is done by iterating each entry and * comparing the names. * * @return DirectoryEntry or null in case its not found * @throws NoSuchFileOrDirectory * @throws FileNameTooLong */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; directoryEntries.release(newEntry); accessData().unlockHierarchyChanges(); directoryLock.writeLock().unlock(); } public boolean isEmptyDirectory() { int count = 0; directoryLock.readLock().lock(); for (@SuppressWarnings("unused") DirectoryEntry dir : iterateDirectory()) { count += 1; if (count >= 3) { directoryLock.readLock().unlock(); return false; } } directoryLock.readLock().unlock(); return true; } /** * Lookup name in directory. This is done by iterating each entry and * comparing the names. * * @return DirectoryEntry or null in case its not found * @throws NoSuchFileOrDirectory * @throws FileNameTooLong */
public DirectoryEntry lookup(String name) throws NoSuchFileOrDirectory, FileNameTooLong {
irq0/jext2
src/jext2/DirectoryInode.java
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong;
return true; } @Override public boolean isRegularFile() { return false; } /** * Unlink inode from directory. May cause inode destruction. Inode can * be any kind of inode except directories. * * @param inode inode to unlink * @param name name of the directory entry */ public void unLinkOther(Inode inode, String name) throws JExt2Exception { if (inode.isDirectory()) throw new IllegalArgumentException("Use unLinkDir for directories"); unlink(inode, name); } /** * Remove a subdirectory inode from directory. May cause inode destruction * * @see #isEmptyDirectory() * @param inode Subdirectory inode to be unlinked * @param name name of the directory entry * @throws DirectoryNotEmpty Well, you can't unlink non-empty directories. * "." and ".." entries don't count. */
// Path: src/jext2/exceptions/DirectoryNotEmpty.java // public class DirectoryNotEmpty extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOTEMPTY; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileExists.java // public class FileExists extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EEXIST; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/TooManyLinks.java // public class TooManyLinks extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EMLINK; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryInode.java import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; return true; } @Override public boolean isRegularFile() { return false; } /** * Unlink inode from directory. May cause inode destruction. Inode can * be any kind of inode except directories. * * @param inode inode to unlink * @param name name of the directory entry */ public void unLinkOther(Inode inode, String name) throws JExt2Exception { if (inode.isDirectory()) throw new IllegalArgumentException("Use unLinkDir for directories"); unlink(inode, name); } /** * Remove a subdirectory inode from directory. May cause inode destruction * * @see #isEmptyDirectory() * @param inode Subdirectory inode to be unlinked * @param name name of the directory entry * @throws DirectoryNotEmpty Well, you can't unlink non-empty directories. * "." and ".." entries don't count. */
public void unLinkDir(DirectoryInode inode, String name) throws JExt2Exception, DirectoryNotEmpty {
irq0/jext2
src/jext2/JExt2.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.IoError; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; class JExt2 { private String blockDevFilename; private Superblock superblock; private BlockGroupAccess blockGroups; private void initializeFilesystem(String filename) { try { blockDevFilename = filename; RandomAccessFile blockDevFile = new RandomAccessFile(filename, "rw"); FileChannel blockDev = blockDevFile.getChannel(); BlockAccess blocks = new BlockAccess(blockDev); superblock = Superblock.fromBlockAccess(blocks); blocks.initialize(superblock); blockGroups = BlockGroupAccess.getInstance(); blockGroups.readDescriptors(); } catch (java.io.FileNotFoundException e) { System.out.println("Cannot open block device.. exiting"); System.exit(23);
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/JExt2.java import jext2.exceptions.IoError; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; class JExt2 { private String blockDevFilename; private Superblock superblock; private BlockGroupAccess blockGroups; private void initializeFilesystem(String filename) { try { blockDevFilename = filename; RandomAccessFile blockDevFile = new RandomAccessFile(filename, "rw"); FileChannel blockDev = blockDevFile.getChannel(); BlockAccess blocks = new BlockAccess(blockDev); superblock = Superblock.fromBlockAccess(blocks); blocks.initialize(superblock); blockGroups = BlockGroupAccess.getInstance(); blockGroups.readDescriptors(); } catch (java.io.FileNotFoundException e) { System.out.println("Cannot open block device.. exiting"); System.exit(23);
} catch (IoError e) {
irq0/jext2
src/jext2/DataBlockAccess.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
public class DataBlockIterator implements Iterator<Long>, Iterable<Long>{ Inode inode; long remaining; long current; int locks; LinkedList<Long> blocks; /* cache for block nrs */ DataBlockIterator(DataInode inode, long start) { this.inode = inode; this.current = start; this.remaining = inode.getBlocks()/(superblock.getBlocksize()/512); } DataBlockIterator(DataInode inode) { this(inode , -1); } @Override public boolean hasNext() { fetchNext(); return ((remaining > 0) || ((blocks != null) && (blocks.size() > 0))); } private void fetchNext() { try { if (remaining > 0) { /* still blocks to fetch */ if (blocks == null || blocks.size() == 0) { /* blockNr cache empty */ try { blocks = getBlocks(current + 1, remaining); unlockHierarchyChanges();
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataBlockAccess.java import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public class DataBlockIterator implements Iterator<Long>, Iterable<Long>{ Inode inode; long remaining; long current; int locks; LinkedList<Long> blocks; /* cache for block nrs */ DataBlockIterator(DataInode inode, long start) { this.inode = inode; this.current = start; this.remaining = inode.getBlocks()/(superblock.getBlocksize()/512); } DataBlockIterator(DataInode inode) { this(inode , -1); } @Override public boolean hasNext() { fetchNext(); return ((remaining > 0) || ((blocks != null) && (blocks.size() > 0))); } private void fetchNext() { try { if (remaining > 0) { /* still blocks to fetch */ if (blocks == null || blocks.size() == 0) { /* blockNr cache empty */ try { blocks = getBlocks(current + 1, remaining); unlockHierarchyChanges();
} catch (FileTooLarge e) {
irq0/jext2
src/jext2/DataBlockAccess.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
DataBlockIterator(DataInode inode) { this(inode , -1); } @Override public boolean hasNext() { fetchNext(); return ((remaining > 0) || ((blocks != null) && (blocks.size() > 0))); } private void fetchNext() { try { if (remaining > 0) { /* still blocks to fetch */ if (blocks == null || blocks.size() == 0) { /* blockNr cache empty */ try { blocks = getBlocks(current + 1, remaining); unlockHierarchyChanges(); } catch (FileTooLarge e) { blocks = null; } if (blocks == null) { remaining = 0; return; } remaining -= blocks.size(); current += blocks.size(); } }
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataBlockAccess.java import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; DataBlockIterator(DataInode inode) { this(inode , -1); } @Override public boolean hasNext() { fetchNext(); return ((remaining > 0) || ((blocks != null) && (blocks.size() > 0))); } private void fetchNext() { try { if (remaining > 0) { /* still blocks to fetch */ if (blocks == null || blocks.size() == 0) { /* blockNr cache empty */ try { blocks = getBlocks(current + 1, remaining); unlockHierarchyChanges(); } catch (FileTooLarge e) { blocks = null; } if (blocks == null) { remaining = 0; return; } remaining -= blocks.size(); current += blocks.size(); } }
} catch (JExt2Exception e) {
irq0/jext2
src/jext2/DataBlockAccess.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
throw new RuntimeException("blockToPath: file block number < 0"); } else if (fileBlockNr < Constants.EXT2_NDIR_BLOCKS) { return new int[] { (int)fileBlockNr }; } else if ((fileBlockNr -= directBlocks) < indirectBlocks) { return new int[] { Constants.EXT2_IND_BLOCK, (int)fileBlockNr }; } else if ((fileBlockNr -= indirectBlocks) < doubleBlocks) { return new int[] { Constants.EXT2_DIND_BLOCK, (int)fileBlockNr / ptrs, (int)fileBlockNr % ptrs }; } else if ((fileBlockNr -= doubleBlocks) < trippleBlocks) { return new int[] { Constants.EXT2_TIND_BLOCK, (int)fileBlockNr / (ptrs*ptrs), ((int)fileBlockNr / ptrs) % ptrs , (int)fileBlockNr % ptrs }; } else { throw new FileTooLarge(); } } /** * Read the chain of indirect blocks leading to data * @param inode Inode in question * @param offsets offsets of pointers in inode/indirect blocks * @return array of length depth with block numbers on the path. * array[depth-1] is data block number rest is the indirection on the path. * * If the chain is incomplete return.length < offsets.length */ @NotThreadSafe(useLock=true)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataBlockAccess.java import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; throw new RuntimeException("blockToPath: file block number < 0"); } else if (fileBlockNr < Constants.EXT2_NDIR_BLOCKS) { return new int[] { (int)fileBlockNr }; } else if ((fileBlockNr -= directBlocks) < indirectBlocks) { return new int[] { Constants.EXT2_IND_BLOCK, (int)fileBlockNr }; } else if ((fileBlockNr -= indirectBlocks) < doubleBlocks) { return new int[] { Constants.EXT2_DIND_BLOCK, (int)fileBlockNr / ptrs, (int)fileBlockNr % ptrs }; } else if ((fileBlockNr -= doubleBlocks) < trippleBlocks) { return new int[] { Constants.EXT2_TIND_BLOCK, (int)fileBlockNr / (ptrs*ptrs), ((int)fileBlockNr / ptrs) % ptrs , (int)fileBlockNr % ptrs }; } else { throw new FileTooLarge(); } } /** * Read the chain of indirect blocks leading to data * @param inode Inode in question * @param offsets offsets of pointers in inode/indirect blocks * @return array of length depth with block numbers on the path. * array[depth-1] is data block number rest is the indirection on the path. * * If the chain is incomplete return.length < offsets.length */ @NotThreadSafe(useLock=true)
private long[] getBranch(int[] offsets) throws IoError {
irq0/jext2
src/jext2/DataBlockAccess.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
/* No such thing, so let's try location of indirect block */ if (depth > 1) return blockNrs[depth-1]; /* It is going to be refered from inode itself? OK just put i into * the same cylinder group then */ long bgStart = BlockGroupDescriptor.firstBlock(inode.getBlockGroup()); long colour = (Filesystem.getPID() % 16) * (superblock.getBlocksPerGroup() / 16); return bgStart + colour; } /** Allocate and set up a chain of blocks. * @param inode owner * @param num depth of the chain (number of blocks to allocate) * @param goal gloal block * @param offsets offsets in the indirection chain * @param blockNrs chain of allready allocated blocks * @throws NoSpaceLeftOnDevice * * This function allocates num blocks, zeros out all but the last one, links * them into a chain and writes them to disk. */ @NotThreadSafe(useLock=true) private LinkedList<Long> allocBranch(int num, long goal, int[] offsets, long[] blockNrs)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataBlockAccess.java import jext2.annotations.MustReturnLock; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.Iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /* No such thing, so let's try location of indirect block */ if (depth > 1) return blockNrs[depth-1]; /* It is going to be refered from inode itself? OK just put i into * the same cylinder group then */ long bgStart = BlockGroupDescriptor.firstBlock(inode.getBlockGroup()); long colour = (Filesystem.getPID() % 16) * (superblock.getBlocksPerGroup() / 16); return bgStart + colour; } /** Allocate and set up a chain of blocks. * @param inode owner * @param num depth of the chain (number of blocks to allocate) * @param goal gloal block * @param offsets offsets in the indirection chain * @param blockNrs chain of allready allocated blocks * @throws NoSpaceLeftOnDevice * * This function allocates num blocks, zeros out all but the last one, links * them into a chain and writes them to disk. */ @NotThreadSafe(useLock=true) private LinkedList<Long> allocBranch(int num, long goal, int[] offsets, long[] blockNrs)
throws JExt2Exception, NoSpaceLeftOnDevice {
irq0/jext2
src/jext2/InodeAccess.java
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class InodeAccess extends DataStructureAccessProvider<Long, Inode>{ private static InodeAccess _instance = new InodeAccess(); private static Superblock superblock = Superblock.getInstance(); private static BlockAccess blocks = BlockAccess.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private InodeAccess() { super(1000); }
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/InodeAccess.java import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class InodeAccess extends DataStructureAccessProvider<Long, Inode>{ private static InodeAccess _instance = new InodeAccess(); private static Superblock superblock = Superblock.getInstance(); private static BlockAccess blocks = BlockAccess.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private InodeAccess() { super(1000); }
public static Inode readFromByteBuffer(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/InodeAccess.java
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class InodeAccess extends DataStructureAccessProvider<Long, Inode>{ private static InodeAccess _instance = new InodeAccess(); private static Superblock superblock = Superblock.getInstance(); private static BlockAccess blocks = BlockAccess.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private InodeAccess() { super(1000); } public static Inode readFromByteBuffer(ByteBuffer buf) throws IoError { Mode mode = Mode.createWithNumericValue(Ext2fsDataTypes.getLE16(buf, 0)); /* NOTE: mode is first field in inode */ if (mode.isDirectory()) { return DirectoryInode.fromByteBuffer(buf, 0); } else if (mode.isRegular()) { return RegularInode.fromByteBuffer(buf, 0); } else if (mode.isSymlink()) { return SymlinkInode.fromByteBuffer(buf, 0); } else { return Inode.fromByteBuffer(buf, 0); } }
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/InodeAccess.java import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class InodeAccess extends DataStructureAccessProvider<Long, Inode>{ private static InodeAccess _instance = new InodeAccess(); private static Superblock superblock = Superblock.getInstance(); private static BlockAccess blocks = BlockAccess.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private InodeAccess() { super(1000); } public static Inode readFromByteBuffer(ByteBuffer buf) throws IoError { Mode mode = Mode.createWithNumericValue(Ext2fsDataTypes.getLE16(buf, 0)); /* NOTE: mode is first field in inode */ if (mode.isDirectory()) { return DirectoryInode.fromByteBuffer(buf, 0); } else if (mode.isRegular()) { return RegularInode.fromByteBuffer(buf, 0); } else if (mode.isSymlink()) { return SymlinkInode.fromByteBuffer(buf, 0); } else { return Inode.fromByteBuffer(buf, 0); } }
public static Inode readByIno(long ino) throws IoError, InvalidArgument {
irq0/jext2
src/jext2/InodeAccess.java
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory;
Inode inode = InodeAccess.readFromByteBuffer(rawInode); // TODO check for NOENT exception inode.setBlockGroup(group); inode.setIno(ino); inode.setBlockNr(absBlock); inode.setOffset(relOffset); return inode; } public static InodeAccess getInstance() { return _instance; } public static Inode readRootInode() throws IoError { try { return readByIno(Constants.EXT2_ROOT_INO); } catch (InvalidArgument e) { throw new RuntimeException("should not happen"); } } public Inode getOpened(long ino) { return get(ino); }
// Path: src/jext2/exceptions/InvalidArgument.java // public class InvalidArgument extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EINVAL; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSuchFileOrDirectory.java // public class NoSuchFileOrDirectory extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO = Errno.ENOENT; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/InodeAccess.java import java.nio.ByteBuffer; import java.util.logging.Level; import jext2.exceptions.InvalidArgument; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSuchFileOrDirectory; Inode inode = InodeAccess.readFromByteBuffer(rawInode); // TODO check for NOENT exception inode.setBlockGroup(group); inode.setIno(ino); inode.setBlockNr(absBlock); inode.setOffset(relOffset); return inode; } public static InodeAccess getInstance() { return _instance; } public static Inode readRootInode() throws IoError { try { return readByIno(Constants.EXT2_ROOT_INO); } catch (InvalidArgument e) { throw new RuntimeException("should not happen"); } } public Inode getOpened(long ino) { return get(ino); }
public Inode openInode(long ino) throws JExt2Exception {
irq0/jext2
src/fusejext2/FuseJExt2.java
// Path: src/jext2/Filesystem.java // public class Filesystem { // private static Charset charset = Charset.defaultCharset(); // private static Logger logger; // // static class Jext2Formatter extends Formatter { // private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // // @Override // public String format(LogRecord record) { // StringBuilder s = new StringBuilder(1000) // // Timestamp // .append(df.format(new Date(record.getMillis()))) // .append(" ") // // // Source class name // .append("[") // .append(record.getSourceClassName()) // .append(".") // .append(record.getSourceMethodName()) // .append("]") // .append(" ") // // // Loglevel // .append(record.getLevel()) // .append(" ") // // // Message // .append(formatMessage(record)) // .append("\n"); // return s.toString(); // } // } // // public static Charset getCharset() { // return charset; // } // public static void setCharset(Charset charset) { // Filesystem.charset = charset; // } // // /** // * Get the PID of the running process // */ // public static long getPID() { // String appName = ManagementFactory.getRuntimeMXBean().getName(); // String strPid = appName.substring(0, appName.indexOf('@')-1); // return Long.parseLong(strPid); // } // // public static void initializeLoggingToFile(String logfile) throws IOException { // FileHandler handler = new FileHandler(logfile); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLoggingToConsole() { // ConsoleHandler handler = new ConsoleHandler(); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLogging() { // LogManager logman = LogManager.getLogManager(); // logman.reset(); // // logger = Logger.getLogger("jext2"); // logger.setLevel(Level.WARNING); // } // // public static void setLogLevel(String level) { // logger.setLevel(Level.parse(level)); // } // // public static Logger getLogger() { // return logger; // } // }
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Constructor; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.logging.Handler; import java.util.logging.Logger; import jext2.Filesystem; import jlowfuse.JLowFuse; import jlowfuse.JLowFuseArgs; import jlowfuse.async.DefaultTaskImplementations; import jlowfuse.async.TaskImplementations; import jlowfuse.async.tasks.JLowFuseTask; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import fuse.Fuse; import fuse.SWIGTYPE_p_fuse_chan; import fuse.SWIGTYPE_p_fuse_session; import fuse.Session;
} catch (IOException e) { System.err.println(Arrays.toString(e.getStackTrace())); System.err.println(e.getLocalizedMessage()); } } private void shutdownThreadPool() { logger.info("Shutting down thread pool"); service.shutdown(); try { logger.info("Waiting for "+ (service.getActiveCount()+service.getQueue().size()) + " tasks to finish"); System.out.println("Awaiting Termination... Queued: " + service.getQueue() +" Running: " + service.getActiveCount()); service.awaitTermination(120, TimeUnit.SECONDS); } catch (InterruptedException e) { System.err.println("Thread pool shutdown interrupted!"); System.err.println(Arrays.toString(e.getStackTrace())); } } private void shutdownFuse() { logger.info("Fuse shutdown, Unmounting.."); Session.removeChan(chan); Session.exit(sess); Fuse.unmount(mountpoint, chan); } private void flushLog() {
// Path: src/jext2/Filesystem.java // public class Filesystem { // private static Charset charset = Charset.defaultCharset(); // private static Logger logger; // // static class Jext2Formatter extends Formatter { // private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // // @Override // public String format(LogRecord record) { // StringBuilder s = new StringBuilder(1000) // // Timestamp // .append(df.format(new Date(record.getMillis()))) // .append(" ") // // // Source class name // .append("[") // .append(record.getSourceClassName()) // .append(".") // .append(record.getSourceMethodName()) // .append("]") // .append(" ") // // // Loglevel // .append(record.getLevel()) // .append(" ") // // // Message // .append(formatMessage(record)) // .append("\n"); // return s.toString(); // } // } // // public static Charset getCharset() { // return charset; // } // public static void setCharset(Charset charset) { // Filesystem.charset = charset; // } // // /** // * Get the PID of the running process // */ // public static long getPID() { // String appName = ManagementFactory.getRuntimeMXBean().getName(); // String strPid = appName.substring(0, appName.indexOf('@')-1); // return Long.parseLong(strPid); // } // // public static void initializeLoggingToFile(String logfile) throws IOException { // FileHandler handler = new FileHandler(logfile); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLoggingToConsole() { // ConsoleHandler handler = new ConsoleHandler(); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLogging() { // LogManager logman = LogManager.getLogManager(); // logman.reset(); // // logger = Logger.getLogger("jext2"); // logger.setLevel(Level.WARNING); // } // // public static void setLogLevel(String level) { // logger.setLevel(Level.parse(level)); // } // // public static Logger getLogger() { // return logger; // } // } // Path: src/fusejext2/FuseJExt2.java import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Constructor; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.logging.Handler; import java.util.logging.Logger; import jext2.Filesystem; import jlowfuse.JLowFuse; import jlowfuse.JLowFuseArgs; import jlowfuse.async.DefaultTaskImplementations; import jlowfuse.async.TaskImplementations; import jlowfuse.async.tasks.JLowFuseTask; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import fuse.Fuse; import fuse.SWIGTYPE_p_fuse_chan; import fuse.SWIGTYPE_p_fuse_session; import fuse.Session; } catch (IOException e) { System.err.println(Arrays.toString(e.getStackTrace())); System.err.println(e.getLocalizedMessage()); } } private void shutdownThreadPool() { logger.info("Shutting down thread pool"); service.shutdown(); try { logger.info("Waiting for "+ (service.getActiveCount()+service.getQueue().size()) + " tasks to finish"); System.out.println("Awaiting Termination... Queued: " + service.getQueue() +" Running: " + service.getActiveCount()); service.awaitTermination(120, TimeUnit.SECONDS); } catch (InterruptedException e) { System.err.println("Thread pool shutdown interrupted!"); System.err.println(Arrays.toString(e.getStackTrace())); } } private void shutdownFuse() { logger.info("Fuse shutdown, Unmounting.."); Session.removeChan(chan); Session.exit(sess); Fuse.unmount(mountpoint, chan); } private void flushLog() {
for (Handler h : Filesystem.getLogger().getHandlers()) {
irq0/jext2
src/fusejext2/tasks/Read.java
// Path: src/jext2/RegularInode.java // public class RegularInode extends DataInode { // protected RegularInode(long blockNr, int offset) throws IoError { // super(blockNr, offset); // } // // public static RegularInode fromByteBuffer(ByteBuffer buf, int offset) throws IoError { // RegularInode inode = new RegularInode(-1, offset); // inode.read(buf); // return inode; // } // // @Override // public short getFileType() { // return DirectoryEntry.FILETYPE_REG_FILE; // } // // @Override // public boolean isSymlink() { // return false; // } // // @Override // public boolean isDirectory() { // return false; // } // // @Override // public boolean isRegularFile() { // return true; // } // // /** // * Set size. For regular inodes the size is stored in i_size and i_dir_acl // * // */ // @Override // public void setSize(long newsize) { // super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); // super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); // } // // @Override // public long getSize() { // return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); // } // // /** // * Set size and truncate. // * @param size new size // * @throws FileTooLarge // */ // @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is // public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge { // if (size < 0) // throw new IllegalArgumentException("Try to set negative file size"); // long oldSize = getSize(); // setSize(size); // if (oldSize > size) // accessData().truncate(size); // } // // /** // * Create empty Inode. Initialize *Times, block array. // */ // public static RegularInode createEmpty() throws IoError { // RegularInode inode = new RegularInode(-1, -1); // Date now = new Date(); // // inode.setModificationTime(now); // inode.setAccessTime(now); // inode.setStatusChangeTime(now); // inode.setDeletionTime(new Date(0)); // inode.setMode(new ModeBuilder().regularFile().create()); // inode.setBlock(new long[Constants.EXT2_N_BLOCKS]); // // return inode; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // }
import java.nio.ByteBuffer; import jext2.RegularInode; import jext2.exceptions.JExt2Exception; import jlowfuse.FuseReq; import jlowfuse.Reply; import fuse.FileInfo; import fusejext2.Jext2Context;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Read extends jlowfuse.async.tasks.Read<Jext2Context> { public Read(FuseReq req, long ino, long size, long off, FileInfo fi) { super(req, ino, size, off, fi); } @Override public void run() { try {
// Path: src/jext2/RegularInode.java // public class RegularInode extends DataInode { // protected RegularInode(long blockNr, int offset) throws IoError { // super(blockNr, offset); // } // // public static RegularInode fromByteBuffer(ByteBuffer buf, int offset) throws IoError { // RegularInode inode = new RegularInode(-1, offset); // inode.read(buf); // return inode; // } // // @Override // public short getFileType() { // return DirectoryEntry.FILETYPE_REG_FILE; // } // // @Override // public boolean isSymlink() { // return false; // } // // @Override // public boolean isDirectory() { // return false; // } // // @Override // public boolean isRegularFile() { // return true; // } // // /** // * Set size. For regular inodes the size is stored in i_size and i_dir_acl // * // */ // @Override // public void setSize(long newsize) { // super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); // super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); // } // // @Override // public long getSize() { // return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); // } // // /** // * Set size and truncate. // * @param size new size // * @throws FileTooLarge // */ // @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is // public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge { // if (size < 0) // throw new IllegalArgumentException("Try to set negative file size"); // long oldSize = getSize(); // setSize(size); // if (oldSize > size) // accessData().truncate(size); // } // // /** // * Create empty Inode. Initialize *Times, block array. // */ // public static RegularInode createEmpty() throws IoError { // RegularInode inode = new RegularInode(-1, -1); // Date now = new Date(); // // inode.setModificationTime(now); // inode.setAccessTime(now); // inode.setStatusChangeTime(now); // inode.setDeletionTime(new Date(0)); // inode.setMode(new ModeBuilder().regularFile().create()); // inode.setBlock(new long[Constants.EXT2_N_BLOCKS]); // // return inode; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // } // Path: src/fusejext2/tasks/Read.java import java.nio.ByteBuffer; import jext2.RegularInode; import jext2.exceptions.JExt2Exception; import jlowfuse.FuseReq; import jlowfuse.Reply; import fuse.FileInfo; import fusejext2.Jext2Context; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Read extends jlowfuse.async.tasks.Read<Jext2Context> { public Read(FuseReq req, long ino, long size, long off, FileInfo fi) { super(req, ino, size, off, fi); } @Override public void run() { try {
RegularInode inode = (RegularInode)(context.inodes.getOpened(ino));
irq0/jext2
src/fusejext2/tasks/Read.java
// Path: src/jext2/RegularInode.java // public class RegularInode extends DataInode { // protected RegularInode(long blockNr, int offset) throws IoError { // super(blockNr, offset); // } // // public static RegularInode fromByteBuffer(ByteBuffer buf, int offset) throws IoError { // RegularInode inode = new RegularInode(-1, offset); // inode.read(buf); // return inode; // } // // @Override // public short getFileType() { // return DirectoryEntry.FILETYPE_REG_FILE; // } // // @Override // public boolean isSymlink() { // return false; // } // // @Override // public boolean isDirectory() { // return false; // } // // @Override // public boolean isRegularFile() { // return true; // } // // /** // * Set size. For regular inodes the size is stored in i_size and i_dir_acl // * // */ // @Override // public void setSize(long newsize) { // super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); // super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); // } // // @Override // public long getSize() { // return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); // } // // /** // * Set size and truncate. // * @param size new size // * @throws FileTooLarge // */ // @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is // public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge { // if (size < 0) // throw new IllegalArgumentException("Try to set negative file size"); // long oldSize = getSize(); // setSize(size); // if (oldSize > size) // accessData().truncate(size); // } // // /** // * Create empty Inode. Initialize *Times, block array. // */ // public static RegularInode createEmpty() throws IoError { // RegularInode inode = new RegularInode(-1, -1); // Date now = new Date(); // // inode.setModificationTime(now); // inode.setAccessTime(now); // inode.setStatusChangeTime(now); // inode.setDeletionTime(new Date(0)); // inode.setMode(new ModeBuilder().regularFile().create()); // inode.setBlock(new long[Constants.EXT2_N_BLOCKS]); // // return inode; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // }
import java.nio.ByteBuffer; import jext2.RegularInode; import jext2.exceptions.JExt2Exception; import jlowfuse.FuseReq; import jlowfuse.Reply; import fuse.FileInfo; import fusejext2.Jext2Context;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Read extends jlowfuse.async.tasks.Read<Jext2Context> { public Read(FuseReq req, long ino, long size, long off, FileInfo fi) { super(req, ino, size, off, fi); } @Override public void run() { try { RegularInode inode = (RegularInode)(context.inodes.getOpened(ino)); // TODO the (int) cast is due to the java-no-unsigned problem. upgrade to java 1.7? ByteBuffer buf = inode.readData((int)size, off); Reply.byteBuffer(req, buf, 0, buf.limit());
// Path: src/jext2/RegularInode.java // public class RegularInode extends DataInode { // protected RegularInode(long blockNr, int offset) throws IoError { // super(blockNr, offset); // } // // public static RegularInode fromByteBuffer(ByteBuffer buf, int offset) throws IoError { // RegularInode inode = new RegularInode(-1, offset); // inode.read(buf); // return inode; // } // // @Override // public short getFileType() { // return DirectoryEntry.FILETYPE_REG_FILE; // } // // @Override // public boolean isSymlink() { // return false; // } // // @Override // public boolean isDirectory() { // return false; // } // // @Override // public boolean isRegularFile() { // return true; // } // // /** // * Set size. For regular inodes the size is stored in i_size and i_dir_acl // * // */ // @Override // public void setSize(long newsize) { // super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); // super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); // } // // @Override // public long getSize() { // return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); // } // // /** // * Set size and truncate. // * @param size new size // * @throws FileTooLarge // */ // @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is // public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge { // if (size < 0) // throw new IllegalArgumentException("Try to set negative file size"); // long oldSize = getSize(); // setSize(size); // if (oldSize > size) // accessData().truncate(size); // } // // /** // * Create empty Inode. Initialize *Times, block array. // */ // public static RegularInode createEmpty() throws IoError { // RegularInode inode = new RegularInode(-1, -1); // Date now = new Date(); // // inode.setModificationTime(now); // inode.setAccessTime(now); // inode.setStatusChangeTime(now); // inode.setDeletionTime(new Date(0)); // inode.setMode(new ModeBuilder().regularFile().create()); // inode.setBlock(new long[Constants.EXT2_N_BLOCKS]); // // return inode; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // } // Path: src/fusejext2/tasks/Read.java import java.nio.ByteBuffer; import jext2.RegularInode; import jext2.exceptions.JExt2Exception; import jlowfuse.FuseReq; import jlowfuse.Reply; import fuse.FileInfo; import fusejext2.Jext2Context; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Read extends jlowfuse.async.tasks.Read<Jext2Context> { public Read(FuseReq req, long ino, long size, long off, FileInfo fi) { super(req, ino, size, off, fi); } @Override public void run() { try { RegularInode inode = (RegularInode)(context.inodes.getOpened(ino)); // TODO the (int) cast is due to the java-no-unsigned problem. upgrade to java 1.7? ByteBuffer buf = inode.readData((int)size, off); Reply.byteBuffer(req, buf, 0, buf.limit());
} catch (JExt2Exception e) {
irq0/jext2
src/jext2/InodeAlloc.java
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Inode allocation and deallocation routines * Adapted from the linux kernel implementation. The long comments on * functionality are mostly copied from linux or e2fsprogs */ public class InodeAlloc { private static Superblock superblock = Superblock.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private static BitmapAccess bitmaps = BitmapAccess.getInstance(); private static Logger logger = Filesystem.getLogger(); public static long countFreeInodes() { long count = 0; for (BlockGroupDescriptor group : blockGroups.iterateBlockGroups()) { count += group.getFreeInodesCount(); } return count; } /* * From linux 2.6.36 source: * There are two policies for allocating an inode. If the new inode is * a directory, then a forward search is made for a block group with both * free space and a low directory-to-inode ratio; if that fails, then of * the groups with above-average free space, that group with the fewest * directories already is chosen. * * For other inodes, search forward from the parent directory\'s block * group to find a free inode. */
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/InodeAlloc.java import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Inode allocation and deallocation routines * Adapted from the linux kernel implementation. The long comments on * functionality are mostly copied from linux or e2fsprogs */ public class InodeAlloc { private static Superblock superblock = Superblock.getInstance(); private static BlockGroupAccess blockGroups = BlockGroupAccess.getInstance(); private static BitmapAccess bitmaps = BitmapAccess.getInstance(); private static Logger logger = Filesystem.getLogger(); public static long countFreeInodes() { long count = 0; for (BlockGroupDescriptor group : blockGroups.iterateBlockGroups()) { count += group.getFreeInodesCount(); } return count; } /* * From linux 2.6.36 source: * There are two policies for allocating an inode. If the new inode is * a directory, then a forward search is made for a block group with both * free space and a low directory-to-inode ratio; if that fails, then of * the groups with above-average free space, that group with the fewest * directories already is chosen. * * For other inodes, search forward from the parent directory\'s block * group to find a free inode. */
public static int findGroupDir(Inode parent) throws NoSpaceLeftOnDevice {
irq0/jext2
src/jext2/InodeAlloc.java
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.util.logging.Level; import java.util.logging.Logger;
* * If there are block groups with both free inodes and free blocks counts * not worse than average we return one with smallest directory count. * Otherwise we simply return a random group. * * For the rest rules look so: * * It's OK to put directory into a group unless * it has too many directories already (max_dirs) or * it has too few free inodes left (min_inodes) or * it has too few free blocks left (min_blocks) or * it's already running too large debt (max_debt). * Parent's group is preferred, if it doesn't satisfy these * conditions we search cyclically through the rest. If none * of the groups look good we just look for a group with more * free inodes than average (starting at parent's group). * * Debt is incremented each time we allocate a directory and decremented * when we allocate an inode, within 0--255. */ public static int findGroupOrlov(Inode parent) { // TODO implement me return -1; } /** * Free Inode: Remove data blocks and set bit to 0 * @throws JExt2Exception */
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/InodeAlloc.java import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import java.util.logging.Level; import java.util.logging.Logger; * * If there are block groups with both free inodes and free blocks counts * not worse than average we return one with smallest directory count. * Otherwise we simply return a random group. * * For the rest rules look so: * * It's OK to put directory into a group unless * it has too many directories already (max_dirs) or * it has too few free inodes left (min_inodes) or * it has too few free blocks left (min_blocks) or * it's already running too large debt (max_debt). * Parent's group is preferred, if it doesn't satisfy these * conditions we search cyclically through the rest. If none * of the groups look good we just look for a group with more * free inodes than average (starting at parent's group). * * Debt is incremented each time we allocate a directory and decremented * when we allocate an inode, within 0--255. */ public static int findGroupOrlov(Inode parent) { // TODO implement me return -1; } /** * Free Inode: Remove data blocks and set bit to 0 * @throws JExt2Exception */
static void freeInode(Inode inode) throws JExt2Exception {
irq0/jext2
src/jext2/Bitmap.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import jext2.exceptions.IoError; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.concurrent.locks.ReentrantLock;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class Bitmap extends Block { private boolean dirty = false; private ByteBuffer bmap = ByteBuffer.allocate(Superblock.getInstance().getBlocksize()); private ReentrantLock bmapLock = new ReentrantLock(); @Override
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/Bitmap.java import jext2.exceptions.IoError; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.concurrent.locks.ReentrantLock; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class Bitmap extends Block { private boolean dirty = false; private ByteBuffer bmap = ByteBuffer.allocate(Superblock.getInstance().getBlocksize()); private ReentrantLock bmapLock = new ReentrantLock(); @Override
protected void read(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/exceptions/JExt2Exception.java
// Path: src/jext2/Filesystem.java // public class Filesystem { // private static Charset charset = Charset.defaultCharset(); // private static Logger logger; // // static class Jext2Formatter extends Formatter { // private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // // @Override // public String format(LogRecord record) { // StringBuilder s = new StringBuilder(1000) // // Timestamp // .append(df.format(new Date(record.getMillis()))) // .append(" ") // // // Source class name // .append("[") // .append(record.getSourceClassName()) // .append(".") // .append(record.getSourceMethodName()) // .append("]") // .append(" ") // // // Loglevel // .append(record.getLevel()) // .append(" ") // // // Message // .append(formatMessage(record)) // .append("\n"); // return s.toString(); // } // } // // public static Charset getCharset() { // return charset; // } // public static void setCharset(Charset charset) { // Filesystem.charset = charset; // } // // /** // * Get the PID of the running process // */ // public static long getPID() { // String appName = ManagementFactory.getRuntimeMXBean().getName(); // String strPid = appName.substring(0, appName.indexOf('@')-1); // return Long.parseLong(strPid); // } // // public static void initializeLoggingToFile(String logfile) throws IOException { // FileHandler handler = new FileHandler(logfile); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLoggingToConsole() { // ConsoleHandler handler = new ConsoleHandler(); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLogging() { // LogManager logman = LogManager.getLogManager(); // logman.reset(); // // logger = Logger.getLogger("jext2"); // logger.setLevel(Level.WARNING); // } // // public static void setLogLevel(String level) { // logger.setLevel(Level.parse(level)); // } // // public static Logger getLogger() { // return logger; // } // }
import jext2.Filesystem; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2.exceptions; public class JExt2Exception extends Exception { protected static final int ERRNO = -1; private static final long serialVersionUID = -7429088074385678308L;
// Path: src/jext2/Filesystem.java // public class Filesystem { // private static Charset charset = Charset.defaultCharset(); // private static Logger logger; // // static class Jext2Formatter extends Formatter { // private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // // @Override // public String format(LogRecord record) { // StringBuilder s = new StringBuilder(1000) // // Timestamp // .append(df.format(new Date(record.getMillis()))) // .append(" ") // // // Source class name // .append("[") // .append(record.getSourceClassName()) // .append(".") // .append(record.getSourceMethodName()) // .append("]") // .append(" ") // // // Loglevel // .append(record.getLevel()) // .append(" ") // // // Message // .append(formatMessage(record)) // .append("\n"); // return s.toString(); // } // } // // public static Charset getCharset() { // return charset; // } // public static void setCharset(Charset charset) { // Filesystem.charset = charset; // } // // /** // * Get the PID of the running process // */ // public static long getPID() { // String appName = ManagementFactory.getRuntimeMXBean().getName(); // String strPid = appName.substring(0, appName.indexOf('@')-1); // return Long.parseLong(strPid); // } // // public static void initializeLoggingToFile(String logfile) throws IOException { // FileHandler handler = new FileHandler(logfile); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLoggingToConsole() { // ConsoleHandler handler = new ConsoleHandler(); // handler.setFormatter(new Jext2Formatter()); // // logger.addHandler(handler); // } // // public static void initializeLogging() { // LogManager logman = LogManager.getLogManager(); // logman.reset(); // // logger = Logger.getLogger("jext2"); // logger.setLevel(Level.WARNING); // } // // public static void setLogLevel(String level) { // logger.setLevel(Level.parse(level)); // } // // public static Logger getLogger() { // return logger; // } // } // Path: src/jext2/exceptions/JExt2Exception.java import jext2.Filesystem; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2.exceptions; public class JExt2Exception extends Exception { protected static final int ERRNO = -1; private static final long serialVersionUID = -7429088074385678308L;
Logger logger = Filesystem.getLogger();
irq0/jext2
src/jext2/DirectoryEntryAccess.java
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import jext2.exceptions.JExt2Exception;
result = d.value; d.unlock(); } else { d = new Data(); d.lock(); d.usage = 1; d.value = entry; result = entry; table.put(entry.getName(), d); d.unlock(); } return result; } public boolean hasEntry(DirectoryEntry entry) { assert entry != null; if (entry.isUnused()) return true; boolean result; result = table.containsKey(entry.getName()); return result; } @Override
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/DirectoryEntryAccess.java import jext2.exceptions.JExt2Exception; result = d.value; d.unlock(); } else { d = new Data(); d.lock(); d.usage = 1; d.value = entry; result = entry; table.put(entry.getName(), d); d.unlock(); } return result; } public boolean hasEntry(DirectoryEntry entry) { assert entry != null; if (entry.isUnused()) return true; boolean result; result = table.containsKey(entry.getName()); return result; } @Override
protected DirectoryEntry createInstance(String key) throws JExt2Exception {
irq0/jext2
src/fusejext2/tasks/Destroy.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // }
import fusejext2.Jext2Context; import java.util.Date; import jext2.exceptions.IoError;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Destroy extends jlowfuse.async.tasks.Destroy<Jext2Context> { @Override public void run() { try { context.superblock.setLastWrite(new Date()); context.superblock.sync(); context.blockGroups.syncDescriptors(); context.blocks.sync();
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/fusejext2/Jext2Context.java // public class Jext2Context extends Context { // public BlockAccess blocks; // public Superblock superblock; // public BlockGroupAccess blockGroups; // // public FileChannel blockDev; // // public InodeAccess inodes; // // public Jext2Context(FileChannel blockDev) { // this.blockDev = blockDev; // } // } // Path: src/fusejext2/tasks/Destroy.java import fusejext2.Jext2Context; import java.util.Date; import jext2.exceptions.IoError; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2.tasks; public class Destroy extends jlowfuse.async.tasks.Destroy<Jext2Context> { @Override public void run() { try { context.superblock.setLastWrite(new Date()); context.superblock.sync(); context.blockGroups.syncDescriptors(); context.blocks.sync();
} catch (IoError e) {
irq0/jext2
src/jext2/DirectoryEntry.java
// Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import jext2.exceptions.FileNameTooLong; import jext2.exceptions.IoError; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
public boolean isRegularFile() { return getFileType() == FILETYPE_REG_FILE; } public boolean isDirectory() { return getFileType() == FILETYPE_DIR; } public boolean isCharacterDevice() { return getFileType() == FILETYPE_CHRDEV; } public boolean isBlockDevice() { return getFileType() == FILETYPE_BLKDEV; } public boolean isFiFo() { return getFileType() == FILETYPE_FIFO; } public boolean isSocket() { return getFileType() == FILETYPE_SOCK; } public boolean isSymlink() { return getFileType() == FILETYPE_SYMLINK; } @Override
// Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryEntry.java import java.nio.ByteBuffer; import jext2.exceptions.FileNameTooLong; import jext2.exceptions.IoError; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public boolean isRegularFile() { return getFileType() == FILETYPE_REG_FILE; } public boolean isDirectory() { return getFileType() == FILETYPE_DIR; } public boolean isCharacterDevice() { return getFileType() == FILETYPE_CHRDEV; } public boolean isBlockDevice() { return getFileType() == FILETYPE_BLKDEV; } public boolean isFiFo() { return getFileType() == FILETYPE_FIFO; } public boolean isSocket() { return getFileType() == FILETYPE_SOCK; } public boolean isSymlink() { return getFileType() == FILETYPE_SYMLINK; } @Override
protected void read(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/DirectoryEntry.java
// Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import jext2.exceptions.FileNameTooLong; import jext2.exceptions.IoError; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
} public boolean isSocket() { return getFileType() == FILETYPE_SOCK; } public boolean isSymlink() { return getFileType() == FILETYPE_SYMLINK; } @Override protected void read(ByteBuffer buf) throws IoError { this.ino = Ext2fsDataTypes.getLE32U(buf, offset); this.recLen = Ext2fsDataTypes.getLE16U(buf, 4 + offset); this.nameLen = Ext2fsDataTypes.getLE8U(buf, 6 + offset); this.fileType = Ext2fsDataTypes.getLE8U(buf, 7 + offset); this.name = Ext2fsDataTypes.getString(buf, 8 + offset, this.nameLen); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } /** * Create a new directory entry. Note that the name is mandatory because * it dictates the record length on disk */ // TODO make visibility package
// Path: src/jext2/exceptions/FileNameTooLong.java // public class FileNameTooLong extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENAMETOOLONG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DirectoryEntry.java import java.nio.ByteBuffer; import jext2.exceptions.FileNameTooLong; import jext2.exceptions.IoError; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; } public boolean isSocket() { return getFileType() == FILETYPE_SOCK; } public boolean isSymlink() { return getFileType() == FILETYPE_SYMLINK; } @Override protected void read(ByteBuffer buf) throws IoError { this.ino = Ext2fsDataTypes.getLE32U(buf, offset); this.recLen = Ext2fsDataTypes.getLE16U(buf, 4 + offset); this.nameLen = Ext2fsDataTypes.getLE8U(buf, 6 + offset); this.fileType = Ext2fsDataTypes.getLE8U(buf, 7 + offset); this.name = Ext2fsDataTypes.getString(buf, 8 + offset, this.nameLen); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } /** * Create a new directory entry. Note that the name is mandatory because * it dictates the record length on disk */ // TODO make visibility package
public static DirectoryEntry create(String name) throws FileNameTooLong {
irq0/jext2
src/jext2/SymlinkInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/SymlinkInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true)
private String readSlowSymlink() throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/SymlinkInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/SymlinkInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true)
private String readSlowSymlink() throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/SymlinkInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true) private String readSlowSymlink() throws JExt2Exception, FileTooLarge { ByteBuffer buf = readData((int)getSize(), 0); return Ext2fsDataTypes.getString(buf, 0, buf.limit()); } @NotThreadSafe(useLock=true)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/SymlinkInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true) private String readSlowSymlink() throws JExt2Exception, FileTooLarge { ByteBuffer buf = readData((int)getSize(), 0); return Ext2fsDataTypes.getString(buf, 0, buf.limit()); } @NotThreadSafe(useLock=true)
private void writeSlowSymlink(String link, int size) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge {
irq0/jext2
src/jext2/SymlinkInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true) private String readSlowSymlink() throws JExt2Exception, FileTooLarge { ByteBuffer buf = readData((int)getSize(), 0); return Ext2fsDataTypes.getString(buf, 0, buf.limit()); } @NotThreadSafe(useLock=true) private void writeSlowSymlink(String link, int size) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge { ByteBuffer buf = ByteBuffer.allocate(Ext2fsDataTypes.getStringByteLength(link)); Ext2fsDataTypes.putString(buf, link, buf.capacity(), 0); buf.rewind(); writeData(buf, 0); } @NotThreadSafe(useLock=true)
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/SymlinkInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public class SymlinkInode extends DataInode { private String symlink = ""; public int FAST_SYMLINK_MAX=Constants.EXT2_N_BLOCKS * 4; private ReentrantReadWriteLock symlinkLock = new JextReentrantReadWriteLock(true); @NotThreadSafe(useLock=true) private String readSlowSymlink() throws JExt2Exception, FileTooLarge { ByteBuffer buf = readData((int)getSize(), 0); return Ext2fsDataTypes.getString(buf, 0, buf.limit()); } @NotThreadSafe(useLock=true) private void writeSlowSymlink(String link, int size) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge { ByteBuffer buf = ByteBuffer.allocate(Ext2fsDataTypes.getStringByteLength(link)); Ext2fsDataTypes.putString(buf, link, buf.capacity(), 0); buf.rewind(); writeData(buf, 0); } @NotThreadSafe(useLock=true)
private String readFastSymlink(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/Superblock.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.UUID; import java.util.Date; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
} public final void setMountCount(int mountCount) { this.mountCount = mountCount; } public final void setMaxMountCount(int maxMountCount) { this.maxMountCount = maxMountCount; } public final void setLastMount(Date lastMount) { this.lastMount = lastMount; } public final void setLastWrite(Date lastWrite) { this.lastWrite = lastWrite; } public final void setLastMounted(String lastMounted) { this.lastMounted = lastMounted; } public boolean hasFreeBlocks() { long freeBlocks = this.freeBlocksCount; long rootBlocks = this.reservedBlocksCount; if (freeBlocks < rootBlocks + 1) { // TODO support reserve blocks return false; } return true; } @Override
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/Superblock.java import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.UUID; import java.util.Date; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; } public final void setMountCount(int mountCount) { this.mountCount = mountCount; } public final void setMaxMountCount(int maxMountCount) { this.maxMountCount = maxMountCount; } public final void setLastMount(Date lastMount) { this.lastMount = lastMount; } public final void setLastWrite(Date lastWrite) { this.lastWrite = lastWrite; } public final void setLastMounted(String lastMounted) { this.lastMounted = lastMounted; } public boolean hasFreeBlocks() { long freeBlocks = this.freeBlocksCount; long rootBlocks = this.reservedBlocksCount; if (freeBlocks < rootBlocks + 1) { // TODO support reserve blocks return false; } return true; } @Override
protected void read(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/RegularInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import java.nio.ByteBuffer; import java.util.Date; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception;
public boolean isDirectory() { return false; } @Override public boolean isRegularFile() { return true; } /** * Set size. For regular inodes the size is stored in i_size and i_dir_acl * */ @Override public void setSize(long newsize) { super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); } @Override public long getSize() { return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); } /** * Set size and truncate. * @param size new size * @throws FileTooLarge */ @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/RegularInode.java import java.nio.ByteBuffer; import java.util.Date; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; public boolean isDirectory() { return false; } @Override public boolean isRegularFile() { return true; } /** * Set size. For regular inodes the size is stored in i_size and i_dir_acl * */ @Override public void setSize(long newsize) { super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); } @Override public long getSize() { return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); } /** * Set size and truncate. * @param size new size * @throws FileTooLarge */ @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is
public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/RegularInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import java.nio.ByteBuffer; import java.util.Date; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception;
public boolean isDirectory() { return false; } @Override public boolean isRegularFile() { return true; } /** * Set size. For regular inodes the size is stored in i_size and i_dir_acl * */ @Override public void setSize(long newsize) { super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); } @Override public long getSize() { return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); } /** * Set size and truncate. * @param size new size * @throws FileTooLarge */ @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/RegularInode.java import java.nio.ByteBuffer; import java.util.Date; import jext2.annotations.NotThreadSafe; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; public boolean isDirectory() { return false; } @Override public boolean isRegularFile() { return true; } /** * Set size. For regular inodes the size is stored in i_size and i_dir_acl * */ @Override public void setSize(long newsize) { super.setSize(newsize & Ext2fsDataTypes.LE32_MAX); super.setDirAcl((newsize >>> Ext2fsDataTypes.LE32_SIZE) & Ext2fsDataTypes.LE32_MAX); } @Override public long getSize() { return super.getSize() + (super.getDirAcl() << Ext2fsDataTypes.LE32_SIZE); } /** * Set size and truncate. * @param size new size * @throws FileTooLarge */ @NotThreadSafe(useLock=false) // XXX will be thread safe once truncate is
public void setSizeAndTruncate(long size) throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/BlockGroupDescriptor.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
} public final int getUsedDirsCount() { return this.usedDirsCount; } public final int getBlockGroup() { return this.blockGroup; } void setBlockGroup(int blockGroup) { this.blockGroup = blockGroup; } public void setFreeBlocksCount(int freeBlocksCount) { this.freeBlocksCount = freeBlocksCount; } public void setFreeInodesCount(int freeInodesCount) { this.freeInodesCount = freeInodesCount; } public void setUsedDirsCount(int usedDirsCount) { this.usedDirsCount = usedDirsCount; } public final void setBlockBitmap(long blockBitmap) { this.blockBitmap = blockBitmap; } public final void setInodeBitmap(long inodeBitmap) { this.inodeBitmap = inodeBitmap; } public final void setInodeTable(long inodeTable) { this.inodeTable = inodeTable; } @Override
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/BlockGroupDescriptor.java import java.nio.ByteBuffer; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; } public final int getUsedDirsCount() { return this.usedDirsCount; } public final int getBlockGroup() { return this.blockGroup; } void setBlockGroup(int blockGroup) { this.blockGroup = blockGroup; } public void setFreeBlocksCount(int freeBlocksCount) { this.freeBlocksCount = freeBlocksCount; } public void setFreeInodesCount(int freeInodesCount) { this.freeInodesCount = freeInodesCount; } public void setUsedDirsCount(int usedDirsCount) { this.usedDirsCount = usedDirsCount; } public final void setBlockBitmap(long blockBitmap) { this.blockBitmap = blockBitmap; } public final void setInodeBitmap(long inodeBitmap) { this.inodeBitmap = inodeBitmap; } public final void setInodeTable(long inodeTable) { this.inodeTable = inodeTable; } @Override
protected void read(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/DataInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Base class for inodes with data blocks. Like Symlinks, Directories, Regular Files */ public class DataInode extends Inode { Superblock superblock = Superblock.getInstance(); BlockAccess blockAccess = BlockAccess.getInstance(); DataBlockAccess dataAccess = null; private long[] block; private long blocks = 0; public final long getBlocks() { return this.blocks; } public final long[] getBlock() { return this.block; } public final void setBlocks(long blocks) { this.blocks = blocks; } public final void setBlock(long[] block) { this.block = block; } @Override public boolean hasDataBlocks() { return getBlocks() > 0; } /** * Get the data access provider to read and write to the data area of this * inode */ public DataBlockAccess accessData() { if (dataAccess == null) dataAccess = DataBlockAccess.fromInode(this); return dataAccess; } /** * Read Inode data * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Base class for inodes with data blocks. Like Symlinks, Directories, Regular Files */ public class DataInode extends Inode { Superblock superblock = Superblock.getInstance(); BlockAccess blockAccess = BlockAccess.getInstance(); DataBlockAccess dataAccess = null; private long[] block; private long blocks = 0; public final long getBlocks() { return this.blocks; } public final long[] getBlock() { return this.block; } public final void setBlocks(long blocks) { this.blocks = blocks; } public final void setBlock(long[] block) { this.block = block; } @Override public boolean hasDataBlocks() { return getBlocks() > 0; } /** * Get the data access provider to read and write to the data area of this * inode */ public DataBlockAccess accessData() { if (dataAccess == null) dataAccess = DataBlockAccess.fromInode(this); return dataAccess; } /** * Read Inode data * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */
public ByteBuffer readData(int size, long fileOffset) throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/DataInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Base class for inodes with data blocks. Like Symlinks, Directories, Regular Files */ public class DataInode extends Inode { Superblock superblock = Superblock.getInstance(); BlockAccess blockAccess = BlockAccess.getInstance(); DataBlockAccess dataAccess = null; private long[] block; private long blocks = 0; public final long getBlocks() { return this.blocks; } public final long[] getBlock() { return this.block; } public final void setBlocks(long blocks) { this.blocks = blocks; } public final void setBlock(long[] block) { this.block = block; } @Override public boolean hasDataBlocks() { return getBlocks() > 0; } /** * Get the data access provider to read and write to the data area of this * inode */ public DataBlockAccess accessData() { if (dataAccess == null) dataAccess = DataBlockAccess.fromInode(this); return dataAccess; } /** * Read Inode data * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Base class for inodes with data blocks. Like Symlinks, Directories, Regular Files */ public class DataInode extends Inode { Superblock superblock = Superblock.getInstance(); BlockAccess blockAccess = BlockAccess.getInstance(); DataBlockAccess dataAccess = null; private long[] block; private long blocks = 0; public final long getBlocks() { return this.blocks; } public final long[] getBlock() { return this.block; } public final void setBlocks(long blocks) { this.blocks = blocks; } public final void setBlock(long[] block) { this.block = block; } @Override public boolean hasDataBlocks() { return getBlocks() > 0; } /** * Get the data access provider to read and write to the data area of this * inode */ public DataBlockAccess accessData() { if (dataAccess == null) dataAccess = DataBlockAccess.fromInode(this); return dataAccess; } /** * Read Inode data * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */
public ByteBuffer readData(int size, long fileOffset) throws JExt2Exception, FileTooLarge {
irq0/jext2
src/jext2/DataInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
} catch (IllegalMonitorStateException e) { Logger log = Filesystem.getLogger(); log.warning("IllegalMonitorStateException encountered in readData, inode=" + this); log.warning(String.format("context for exception: blocks=%s i=%d approxBlocks=%d off=%d buf=%s readlock=%s lock.readlock.holds=%s", b, i, approxBlocks, fileOffset, buf, accessData().getHierarchyLock(), accessData().getHierarchyLock().getReadHoldCount())); } if (buf.capacity() == buf.limit()) break; } assert buf.position() == buf.limit() : "Buffer wasn't filled completely"; assert buf.limit() == size : "Read buffer size does not match request size"; if (buf.limit() > getSize()) buf.limit((int)getSize()); buf.rewind(); return buf; } /** * Write data in buffer to disk. This works best when whole blocks which * are a multiple of blocksize in size are written. Partial blocks are * written by first reading the block and then writing the new data * to that buffer than write that new buffer to disk. * @throws NoSpaceLeftOnDevice * @throws FileTooLarge */
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; } catch (IllegalMonitorStateException e) { Logger log = Filesystem.getLogger(); log.warning("IllegalMonitorStateException encountered in readData, inode=" + this); log.warning(String.format("context for exception: blocks=%s i=%d approxBlocks=%d off=%d buf=%s readlock=%s lock.readlock.holds=%s", b, i, approxBlocks, fileOffset, buf, accessData().getHierarchyLock(), accessData().getHierarchyLock().getReadHoldCount())); } if (buf.capacity() == buf.limit()) break; } assert buf.position() == buf.limit() : "Buffer wasn't filled completely"; assert buf.limit() == size : "Read buffer size does not match request size"; if (buf.limit() > getSize()) buf.limit((int)getSize()); buf.rewind(); return buf; } /** * Write data in buffer to disk. This works best when whole blocks which * are a multiple of blocksize in size are written. Partial blocks are * written by first reading the block and then writing the new data * to that buffer than write that new buffer to disk. * @throws NoSpaceLeftOnDevice * @throws FileTooLarge */
public int writeData(ByteBuffer buf, long offset) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge {
irq0/jext2
src/jext2/DataInode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // }
import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice;
blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, onDisk); } else { /* write whole block */ buf.limit(buf.position() + blocksize); blockAccess.writeFromBufferUnsynchronized( (blockNrs.getFirst() & 0xffffffff) * blocksize, buf); } start += 1; startOff = 0; accessData().unlockHierarchyChanges(); } int written = buf.position(); assert written == buf.capacity(); /* increase inode.size if we grew the file */ if (offset + written > getSize()) { /* file grew */ setStatusChangeTime(new Date()); setSize(offset + written); } return written; } protected DataInode(long blockNr, int offset) { super(blockNr, offset); } @Override
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // // Path: src/jext2/exceptions/NoSpaceLeftOnDevice.java // public class NoSpaceLeftOnDevice extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.ENOSPC; // // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/DataInode.java import java.nio.ByteBuffer; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import org.apache.commons.lang.builder.HashCodeBuilder; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, onDisk); } else { /* write whole block */ buf.limit(buf.position() + blocksize); blockAccess.writeFromBufferUnsynchronized( (blockNrs.getFirst() & 0xffffffff) * blocksize, buf); } start += 1; startOff = 0; accessData().unlockHierarchyChanges(); } int written = buf.position(); assert written == buf.capacity(); /* increase inode.size if we grew the file */ if (offset + written > getSize()) { /* file grew */ setStatusChangeTime(new Date()); setSize(offset + written); } return written; } protected DataInode(long blockNr, int offset) { super(blockNr, offset); } @Override
protected void read(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/Inode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception;
} public final void setModificationTime(Date modificationTime) { this.modificationTime = modificationTime; } public final void setDeletionTime(Date deletionTime) { this.deletionTime = deletionTime; } public final void setLinksCount(int linksCount) { this.linksCount = (linksCount < 0) ? 0 : linksCount ; } public final void setFlags(long flags) { this.flags = flags; } public final void setGeneration(long generation) { this.generation = generation; } public final void setUidHigh(int uidHigh) { this.uidHigh = uidHigh; } public final void setGidHigh(int gidHigh) { this.gidHigh = gidHigh; } protected final void setDirAcl(long dirAcl) { this.dirAcl = dirAcl; } public final boolean isDeleted() { return (this.deletionTime.after(new Date(0))); } @Override
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/Inode.java import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; } public final void setModificationTime(Date modificationTime) { this.modificationTime = modificationTime; } public final void setDeletionTime(Date deletionTime) { this.deletionTime = deletionTime; } public final void setLinksCount(int linksCount) { this.linksCount = (linksCount < 0) ? 0 : linksCount ; } public final void setFlags(long flags) { this.flags = flags; } public final void setGeneration(long generation) { this.generation = generation; } public final void setUidHigh(int uidHigh) { this.uidHigh = uidHigh; } public final void setGidHigh(int gidHigh) { this.gidHigh = gidHigh; } protected final void setDirAcl(long dirAcl) { this.dirAcl = dirAcl; } public final boolean isDeleted() { return (this.deletionTime.after(new Date(0))); } @Override
protected void write(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/Inode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception;
return new EqualsBuilder() .append(ino, other.ino) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .appendSuper(super.hashCode()) .append(mode.numeric()) .append(getGid()) .append(getUid()) .append(size) .append(accessTime) .append(changeTime) .append(modificationTime) .append(deletionTime) .append(linksCount) .append(flags) .append(generation) .append(fileAcl) .append(dirAcl) .append(fragmentAddress) .append(blockGroup) .append(ino).toHashCode(); } /** * Delete Inode */
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/Inode.java import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; return new EqualsBuilder() .append(ino, other.ino) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .appendSuper(super.hashCode()) .append(mode.numeric()) .append(getGid()) .append(getUid()) .append(size) .append(accessTime) .append(changeTime) .append(modificationTime) .append(deletionTime) .append(linksCount) .append(flags) .append(generation) .append(fileAcl) .append(dirAcl) .append(fragmentAddress) .append(blockGroup) .append(ino).toHashCode(); } /** * Delete Inode */
public synchronized void delete() throws JExt2Exception {
irq0/jext2
src/jext2/Inode.java
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception;
.append(size) .append(accessTime) .append(changeTime) .append(modificationTime) .append(deletionTime) .append(linksCount) .append(flags) .append(generation) .append(fileAcl) .append(dirAcl) .append(fragmentAddress) .append(blockGroup) .append(ino).toHashCode(); } /** * Delete Inode */ public synchronized void delete() throws JExt2Exception { if (this.isDeleted()) return; setDeletionTime(new Date()); setSize(0); if (hasDataBlocks()) { DataInode d = (DataInode)this; try { d.accessData().truncate(0); assert d.getBlocks() == 0;
// Path: src/jext2/exceptions/FileTooLarge.java // public class FileTooLarge extends JExt2Exception { // static final long serialVersionUID = 42; // protected final static int ERRNO = Errno.EFBIG; // // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // // Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/Inode.java import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.util.Date; import java.nio.ByteBuffer; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; .append(size) .append(accessTime) .append(changeTime) .append(modificationTime) .append(deletionTime) .append(linksCount) .append(flags) .append(generation) .append(fileAcl) .append(dirAcl) .append(fragmentAddress) .append(blockGroup) .append(ino).toHashCode(); } /** * Delete Inode */ public synchronized void delete() throws JExt2Exception { if (this.isDeleted()) return; setDeletionTime(new Date()); setSize(0); if (hasDataBlocks()) { DataInode d = (DataInode)this; try { d.accessData().truncate(0); assert d.getBlocks() == 0;
} catch (FileTooLarge e) {
irq0/jext2
src/jext2/BitmapAccess.java
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // }
import java.nio.ByteBuffer; import jext2.exceptions.JExt2Exception;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Access methods for bitmaps. Takes care that there is not more than one * Bitmap object for a bitmap * */ public class BitmapAccess extends DataStructureAccessProvider<Long, Bitmap>{ private static BitmapAccess _instance = new BitmapAccess(); private static BlockAccess blocks = BlockAccess.getInstance(); private BitmapAccess() { super(100); }
// Path: src/jext2/exceptions/JExt2Exception.java // public class JExt2Exception extends Exception { // protected static final int ERRNO = -1; // // private static final long serialVersionUID = -7429088074385678308L; // // Logger logger = Filesystem.getLogger(); // // public JExt2Exception() { // log(""); // } // // public JExt2Exception(String msg) { // log(msg); // } // // private void log(String msg) { // if (logger.isLoggable(Level.FINE)) { // StackTraceElement[] stack = getStackTrace(); // // StringBuilder log = new StringBuilder(); // log.append("JEXT2 exception was raised: "); // log.append(this.getClass().getSimpleName()); // log.append(" source="); // log.append(stack[0].getClassName()); // log.append("->"); // log.append(stack[0].getMethodName()); // log.append(" msg="); // log.append(msg); // log.append(" errno="); // log.append(getErrno()); // // logger.fine(log.toString()); // } // } // // public int getErrno() { // throw new RuntimeException("This method should not be executed. " + // "- The errno value defined here is meaningless"); // } // } // Path: src/jext2/BitmapAccess.java import java.nio.ByteBuffer; import jext2.exceptions.JExt2Exception; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Access methods for bitmaps. Takes care that there is not more than one * Bitmap object for a bitmap * */ public class BitmapAccess extends DataStructureAccessProvider<Long, Bitmap>{ private static BitmapAccess _instance = new BitmapAccess(); private static BlockAccess blocks = BlockAccess.getInstance(); private BitmapAccess() { super(100); }
public Bitmap openInodeBitmap(BlockGroupDescriptor group) throws JExt2Exception{
irq0/jext2
src/jext2/Block.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.nio.*; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public abstract class Block { int cleanHashCode = 0; /** block location on filesystem */ protected long nr; public long getBlockNr() { return nr; } public final void setBlockNr(long blockNr) { this.nr = blockNr; } @Override public int hashCode() { return new HashCodeBuilder() .append(nr).toHashCode(); }
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/Block.java import java.nio.*; import jext2.exceptions.IoError; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; public abstract class Block { int cleanHashCode = 0; /** block location on filesystem */ protected long nr; public long getBlockNr() { return nr; } public final void setBlockNr(long blockNr) { this.nr = blockNr; } @Override public int hashCode() { return new HashCodeBuilder() .append(nr).toHashCode(); }
protected void write(ByteBuffer buf) throws IoError {
irq0/jext2
src/jext2/BlockAccess.java
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // }
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.LinkedList; import jext2.annotations.NotThreadSafe; import jext2.exceptions.IoError;
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Access to the filesystem blocks */ public class BlockAccess { private int blocksize = Constants.EXT2_MIN_BLOCK_SIZE; private FileChannel blockdev; private static BlockAccess instance; /** number of pointers in indirection block */ private int ptrs; public BlockAccess(FileChannel blockdev) { if (BlockAccess.instance != null) { throw new RuntimeException("BlockAccess is singleton!"); } this.blockdev = blockdev; BlockAccess.instance = this; } /** Read a block off size specified by setBlocksize() at logical address nr */
// Path: src/jext2/exceptions/IoError.java // public class IoError extends JExt2Exception { // static final long serialVersionUID = 42; // protected static final int ERRNO=Errno.EIO; // public IoError(String msg) { // super(msg); // } // public IoError() { // super(); // } // public int getErrno() { // return ERRNO; // } // } // Path: src/jext2/BlockAccess.java import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.LinkedList; import jext2.annotations.NotThreadSafe; import jext2.exceptions.IoError; /* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; /** * Access to the filesystem blocks */ public class BlockAccess { private int blocksize = Constants.EXT2_MIN_BLOCK_SIZE; private FileChannel blockdev; private static BlockAccess instance; /** number of pointers in indirection block */ private int ptrs; public BlockAccess(FileChannel blockdev) { if (BlockAccess.instance != null) { throw new RuntimeException("BlockAccess is singleton!"); } this.blockdev = blockdev; BlockAccess.instance = this; } /** Read a block off size specified by setBlocksize() at logical address nr */
public ByteBuffer read(long nr) throws IoError {
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/sqlgenerator/DropPrimaryKeyGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.DropPrimaryKeyGenerator; import liquibase.statement.core.DropPrimaryKeyStatement;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class DropPrimaryKeyGeneratorSpanner extends DropPrimaryKeyGenerator { static final String DROP_PK_VALIDATION_ERROR = "Cloud Spanner does not support dropping a primary key from a table"; @Override public ValidationErrors validate( DropPrimaryKeyStatement dropPrimaryKeyStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(dropPrimaryKeyStatement, database, sqlGeneratorChain); errors.addError(DROP_PK_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(DropPrimaryKeyStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/sqlgenerator/DropPrimaryKeyGeneratorSpanner.java import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.DropPrimaryKeyGenerator; import liquibase.statement.core.DropPrimaryKeyStatement; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class DropPrimaryKeyGeneratorSpanner extends DropPrimaryKeyGenerator { static final String DROP_PK_VALIDATION_ERROR = "Cloud Spanner does not support dropping a primary key from a table"; @Override public ValidationErrors validate( DropPrimaryKeyStatement dropPrimaryKeyStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(dropPrimaryKeyStatement, database, sqlGeneratorChain); errors.addError(DROP_PK_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(DropPrimaryKeyStatement statement, Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/datatype/TimestampTypeSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.DateTimeType; import liquibase.ext.spanner.ICloudSpanner; import liquibase.database.Database;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.datatype; public class TimestampTypeSpanner extends DateTimeType { @Override public boolean supports(Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/datatype/TimestampTypeSpanner.java import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.DateTimeType; import liquibase.ext.spanner.ICloudSpanner; import liquibase.database.Database; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.datatype; public class TimestampTypeSpanner extends DateTimeType { @Override public boolean supports(Database database) {
return database instanceof ICloudSpanner;
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/change/DropAllForeignKeyConstraintsChangeSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import com.google.common.base.MoreObjects; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import liquibase.change.ChangeMetaData; import liquibase.change.DatabaseChange; import liquibase.change.core.DropAllForeignKeyConstraintsChange; import liquibase.change.core.DropForeignKeyConstraintChange; import liquibase.database.Database; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.statement.SqlStatement;
package liquibase.ext.spanner.change; @DatabaseChange(name="dropAllForeignKeyConstraints", description = "Drops all foreign key constraints for a table", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "table") public class DropAllForeignKeyConstraintsChangeSpanner extends DropAllForeignKeyConstraintsChange { @Override public boolean supports(Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/change/DropAllForeignKeyConstraintsChangeSpanner.java import com.google.common.base.MoreObjects; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import liquibase.change.ChangeMetaData; import liquibase.change.DatabaseChange; import liquibase.change.core.DropAllForeignKeyConstraintsChange; import liquibase.change.core.DropForeignKeyConstraintChange; import liquibase.database.Database; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.statement.SqlStatement; package liquibase.ext.spanner.change; @DatabaseChange(name="dropAllForeignKeyConstraints", description = "Drops all foreign key constraints for a table", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "table") public class DropAllForeignKeyConstraintsChangeSpanner extends DropAllForeignKeyConstraintsChange { @Override public boolean supports(Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/datatype/BigIntTypeSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.BigIntType; import liquibase.ext.spanner.ICloudSpanner; import liquibase.database.Database;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.datatype; public class BigIntTypeSpanner extends BigIntType { private static final DatabaseDataType INT64 = new DatabaseDataType("INT64"); @Override public boolean supports(Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/datatype/BigIntTypeSpanner.java import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.BigIntType; import liquibase.ext.spanner.ICloudSpanner; import liquibase.database.Database; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.datatype; public class BigIntTypeSpanner extends BigIntType { private static final DatabaseDataType INT64 = new DatabaseDataType("INT64"); @Override public boolean supports(Database database) {
return database instanceof ICloudSpanner;
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/sqlgenerator/CreateViewGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import java.util.ArrayList; import java.util.List; import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.CreateViewGenerator; import liquibase.statement.core.CreateViewStatement;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class CreateViewGeneratorSpanner extends CreateViewGenerator { @Override public Sql[] generateSql(CreateViewStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); if (!statement.isFullDefinition()) { sql.append("CREATE "); if (statement.isReplaceIfExists()) { sql.append("OR REPLACE "); } sql.append("VIEW ") .append( database.escapeViewName( statement.getCatalogName(), statement.getSchemaName(), statement.getViewName())) .append(" SQL SECURITY INVOKER AS "); } sql.append(statement.getSelectQuery()); return new Sql[] { new UnparsedSql(sql.toString(), getAffectedView(statement)) }; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(CreateViewStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/sqlgenerator/CreateViewGeneratorSpanner.java import java.util.ArrayList; import java.util.List; import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.CreateViewGenerator; import liquibase.statement.core.CreateViewStatement; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class CreateViewGeneratorSpanner extends CreateViewGenerator { @Override public Sql[] generateSql(CreateViewStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuilder sql = new StringBuilder(); if (!statement.isFullDefinition()) { sql.append("CREATE "); if (statement.isReplaceIfExists()) { sql.append("OR REPLACE "); } sql.append("VIEW ") .append( database.escapeViewName( statement.getCatalogName(), statement.getSchemaName(), statement.getViewName())) .append(" SQL SECURITY INVOKER AS "); } sql.append(statement.getSelectQuery()); return new Sql[] { new UnparsedSql(sql.toString(), getAffectedView(statement)) }; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(CreateViewStatement statement, Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/sqlgenerator/CreateProcedureGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.CreateProcedureGenerator; import liquibase.statement.core.CreateProcedureStatement;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class CreateProcedureGeneratorSpanner extends CreateProcedureGenerator { static final String CREATE_PROCEDURE_VALIDATION_ERROR = "Cloud Spanner does not support creating procedures"; @Override public ValidationErrors validate( CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = new ValidationErrors(); errors.addError(CREATE_PROCEDURE_VALIDATION_ERROR); return errors; } public Sql[] generateSql(CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { // The normal way of failing the generation by adding a validation error does not work for CREATE PROCEDURE. // This seems to be caused by the fact that CreateProcedureChange is a DbmsTargetedChange. throw new UnexpectedLiquibaseException(CREATE_PROCEDURE_VALIDATION_ERROR); } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(CreateProcedureStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/sqlgenerator/CreateProcedureGeneratorSpanner.java import liquibase.database.Database; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.CreateProcedureGenerator; import liquibase.statement.core.CreateProcedureStatement; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class CreateProcedureGeneratorSpanner extends CreateProcedureGenerator { static final String CREATE_PROCEDURE_VALIDATION_ERROR = "Cloud Spanner does not support creating procedures"; @Override public ValidationErrors validate( CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = new ValidationErrors(); errors.addError(CREATE_PROCEDURE_VALIDATION_ERROR); return errors; } public Sql[] generateSql(CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { // The normal way of failing the generation by adding a validation error does not work for CREATE PROCEDURE. // This seems to be caused by the fact that CreateProcedureChange is a DbmsTargetedChange. throw new UnexpectedLiquibaseException(CREATE_PROCEDURE_VALIDATION_ERROR); } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(CreateProcedureStatement statement, Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/sqlgenerator/DropDefaultValueGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.DropDefaultValueGenerator; import liquibase.statement.core.DropDefaultValueStatement;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class DropDefaultValueGeneratorSpanner extends DropDefaultValueGenerator { static final String DROP_DEFAULT_VALUE_VALIDATION_ERROR = "Cloud Spanner does not support dropping a default value from a column"; @Override public ValidationErrors validate( DropDefaultValueStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(statement, database, sqlGeneratorChain); errors.addError(DROP_DEFAULT_VALUE_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(DropDefaultValueStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/sqlgenerator/DropDefaultValueGeneratorSpanner.java import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.DropDefaultValueGenerator; import liquibase.statement.core.DropDefaultValueStatement; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class DropDefaultValueGeneratorSpanner extends DropDefaultValueGenerator { static final String DROP_DEFAULT_VALUE_VALIDATION_ERROR = "Cloud Spanner does not support dropping a default value from a column"; @Override public ValidationErrors validate( DropDefaultValueStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(statement, database, sqlGeneratorChain); errors.addError(DROP_DEFAULT_VALUE_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(DropDefaultValueStatement statement, Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/sqlgenerator/RenameColumnGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.RenameColumnGenerator; import liquibase.statement.core.RenameColumnStatement;
/** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class RenameColumnGeneratorSpanner extends RenameColumnGenerator { static final String RENAME_COLUMN_VALIDATION_ERROR = "Cloud Spanner does not support renaming a column"; @Override public ValidationErrors validate( RenameColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(statement, database, sqlGeneratorChain); errors.addError(RENAME_COLUMN_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(RenameColumnStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/sqlgenerator/RenameColumnGeneratorSpanner.java import liquibase.database.Database; import liquibase.exception.ValidationErrors; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.RenameColumnGenerator; import liquibase.statement.core.RenameColumnStatement; /** * Copyright 2020 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.sqlgenerator; public class RenameColumnGeneratorSpanner extends RenameColumnGenerator { static final String RENAME_COLUMN_VALIDATION_ERROR = "Cloud Spanner does not support renaming a column"; @Override public ValidationErrors validate( RenameColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors errors = super.validate(statement, database, sqlGeneratorChain); errors.addError(RENAME_COLUMN_VALIDATION_ERROR); return errors; } @Override public int getPriority() { return SqlGenerator.PRIORITY_DATABASE; } @Override public boolean supports(RenameColumnStatement statement, Database database) {
return (database instanceof ICloudSpanner);
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/datatype/ModifyDataTypeGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.sqlgenerator.core.ModifyDataTypeGenerator; import liquibase.statement.core.ModifyDataTypeStatement; import com.google.common.base.MoreObjects; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import liquibase.database.Database; import liquibase.database.jvm.JdbcConnection; import liquibase.datatype.DataTypeFactory; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain;
/** * Copyright 2020 Google LLC * * <p> * 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 * * <p> * https://www.apache.org/licenses/LICENSE-2.0 * * <p> * 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 liquibase.ext.spanner.datatype; public class ModifyDataTypeGeneratorSpanner extends ModifyDataTypeGenerator { @Override public boolean supports(ModifyDataTypeStatement statement, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/datatype/ModifyDataTypeGeneratorSpanner.java import liquibase.sqlgenerator.core.ModifyDataTypeGenerator; import liquibase.statement.core.ModifyDataTypeStatement; import com.google.common.base.MoreObjects; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import liquibase.database.Database; import liquibase.database.jvm.JdbcConnection; import liquibase.datatype.DataTypeFactory; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; /** * Copyright 2020 Google LLC * * <p> * 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 * * <p> * https://www.apache.org/licenses/LICENSE-2.0 * * <p> * 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 liquibase.ext.spanner.datatype; public class ModifyDataTypeGeneratorSpanner extends ModifyDataTypeGenerator { @Override public boolean supports(ModifyDataTypeStatement statement, Database database) {
return database instanceof ICloudSpanner;
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/snapshotgenerator/ForeignKeySnapshotGeneratorSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.exception.DatabaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotGenerator; import liquibase.snapshot.SnapshotGeneratorChain; import liquibase.snapshot.jvm.ForeignKeySnapshotGenerator; import liquibase.structure.DatabaseObject; import liquibase.structure.core.ForeignKey;
/** * Copyright 2021 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.snapshotgenerator; public class ForeignKeySnapshotGeneratorSpanner extends ForeignKeySnapshotGenerator { /** * This generator will be in all chains relating to CloudSpanner, whether or not * the objectType is {@link ForeignKey}. */ @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/snapshotgenerator/ForeignKeySnapshotGeneratorSpanner.java import liquibase.database.Database; import liquibase.exception.DatabaseException; import liquibase.ext.spanner.ICloudSpanner; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotGenerator; import liquibase.snapshot.SnapshotGeneratorChain; import liquibase.snapshot.jvm.ForeignKeySnapshotGenerator; import liquibase.structure.DatabaseObject; import liquibase.structure.core.ForeignKey; /** * Copyright 2021 Google LLC * * <p>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 * * <p>https://www.apache.org/licenses/LICENSE-2.0 * * <p>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 liquibase.ext.spanner.snapshotgenerator; public class ForeignKeySnapshotGeneratorSpanner extends ForeignKeySnapshotGenerator { /** * This generator will be in all chains relating to CloudSpanner, whether or not * the objectType is {@link ForeignKey}. */ @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) {
if (database instanceof ICloudSpanner) {
cloudspannerecosystem/liquibase-spanner
src/main/java/liquibase/ext/spanner/datatype/DoubleTypeSpanner.java
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // }
import liquibase.database.Database; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.DoubleType; import liquibase.ext.spanner.ICloudSpanner;
package liquibase.ext.spanner.datatype; public class DoubleTypeSpanner extends DoubleType { private static final DatabaseDataType FLOAT64 = new DatabaseDataType("FLOAT64"); @Override public boolean supports(Database database) {
// Path: src/main/java/liquibase/ext/spanner/ICloudSpanner.java // public interface ICloudSpanner extends Database { // } // Path: src/main/java/liquibase/ext/spanner/datatype/DoubleTypeSpanner.java import liquibase.database.Database; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.core.DoubleType; import liquibase.ext.spanner.ICloudSpanner; package liquibase.ext.spanner.datatype; public class DoubleTypeSpanner extends DoubleType { private static final DatabaseDataType FLOAT64 = new DatabaseDataType("FLOAT64"); @Override public boolean supports(Database database) {
return database instanceof ICloudSpanner;