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
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor();
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors;
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor(); // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors;
@NotNull private final Set<FieldAttributesProcessor> fieldAttributesProcessors;
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor();
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors; @NotNull private final Set<FieldAttributesProcessor> fieldAttributesProcessors; public FieldAttributesProcessors(@NotNull final FieldAttributesProcessor... fieldAttributesProcessors) { this.fieldAttributesProcessors = new LinkedHashSet<>(asList(fieldAttributesProcessors)); } @NotNull
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor(); // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors; @NotNull private final Set<FieldAttributesProcessor> fieldAttributesProcessors; public FieldAttributesProcessors(@NotNull final FieldAttributesProcessor... fieldAttributesProcessors) { this.fieldAttributesProcessors = new LinkedHashSet<>(asList(fieldAttributesProcessors)); } @NotNull
public List<GccAttribute<GccVariableAttributeName>> processFieldAttributes(@NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor();
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors; @NotNull private final Set<FieldAttributesProcessor> fieldAttributesProcessors; public FieldAttributesProcessors(@NotNull final FieldAttributesProcessor... fieldAttributesProcessors) { this.fieldAttributesProcessors = new LinkedHashSet<>(asList(fieldAttributesProcessors)); } @NotNull
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/FieldAttributesProcessor.java // public interface FieldAttributesProcessor // { // void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/AlignmentFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Alignment = new AlignmentFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/NullCheckFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor NullCheck = new NullCheckFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/PackedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Packed = new PackedFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java // @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor(); // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/FieldAttributesProcessors.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.FieldAttributesProcessor; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.AlignmentFieldAttributesProcessor.Alignment; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.DeprecatedFieldAttributesProcessor.Deprecated; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.NullCheckFieldAttributesProcessor.NullCheck; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.PackedFieldAttributesProcessor.Packed; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.SectionFieldAttributesProcessor.Section; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.ThreadLocalModelFieldAttributesProcessor.ThreadLocalModel; import static com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors.UnusedFieldAttributesProcessor.Unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters; public final class FieldAttributesProcessors { @NotNull public static final FieldAttributesProcessors StaticFieldAttributesProcessors = new FieldAttributesProcessors ( NullCheck, Deprecated, Unused, Alignment, ThreadLocalModel, Section, Packed ); @NotNull public static final FieldAttributesProcessors InstanceFieldAttributesProcessors = StaticFieldAttributesProcessors; @NotNull private final Set<FieldAttributesProcessor> fieldAttributesProcessors; public FieldAttributesProcessors(@NotNull final FieldAttributesProcessor... fieldAttributesProcessors) { this.fieldAttributesProcessors = new LinkedHashSet<>(asList(fieldAttributesProcessors)); } @NotNull
public List<GccAttribute<GccVariableAttributeName>> processFieldAttributes(@NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
@NotNull private static final GccAttribute<GccVariableAttributeName> UnusedAttribute = new GccAttribute<>(unused);
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
@NotNull private static final GccAttribute<GccVariableAttributeName> UnusedAttribute = new GccAttribute<>(unused);
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull private static final GccAttribute<GccVariableAttributeName> UnusedAttribute = new GccAttribute<>(unused); @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor(); private UnusedFieldAttributesProcessor() { } @Override
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/UnusedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.unused; import static java.util.Arrays.asList; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class UnusedFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull private static final GccAttribute<GccVariableAttributeName> UnusedAttribute = new GccAttribute<>(unused); @NotNull public static final FieldAttributesProcessor Unused = new UnusedFieldAttributesProcessor(); private UnusedFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final section section = field.getAnnotation(section.class); if (section == null) { return; } @Nullable final String sectionName = section.value(); if (sectionName == null) { throw new ConversionException("@section must specify a section name (value)"); }
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/SectionFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.section; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class SectionFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor Section = new SectionFieldAttributesProcessor(); private SectionFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final section section = field.getAnnotation(section.class); if (section == null) { return; } @Nullable final String sectionName = section.value(); if (sectionName == null) { throw new ConversionException("@section must specify a section name (value)"); }
gccAttributes.add(new GccAttribute<>(GccVariableAttributeName.section, new GccAttributeParameter(sectionName)));
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/javaModules/StatefulJavaSourceFileVisitor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/warnings/Warnings.java // public interface Warnings extends DiagnosticListener<JavaFileObject> // { // void fatal(@NotNull final FatalCompilationException cause); // // void warn(@NotNull final String warning); // // void information(@NotNull final String information); // }
import com.stormmq.java2c.transpiler.warnings.Warnings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import static java.lang.String.format; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.SKIP_SUBTREE; import static java.util.Locale.ENGLISH;
package com.stormmq.java2c.transpiler.javaModules; public final class StatefulJavaSourceFileVisitor implements FileVisitor<Path> {
// Path: source/transpiler/com/stormmq/java2c/transpiler/warnings/Warnings.java // public interface Warnings extends DiagnosticListener<JavaFileObject> // { // void fatal(@NotNull final FatalCompilationException cause); // // void warn(@NotNull final String warning); // // void information(@NotNull final String information); // } // Path: source/transpiler/com/stormmq/java2c/transpiler/javaModules/StatefulJavaSourceFileVisitor.java import com.stormmq.java2c.transpiler.warnings.Warnings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import static java.lang.String.format; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.SKIP_SUBTREE; import static java.util.Locale.ENGLISH; package com.stormmq.java2c.transpiler.javaModules; public final class StatefulJavaSourceFileVisitor implements FileVisitor<Path> {
@NotNull private final Warnings warnings;
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
@NotNull private static final GccAttribute<GccVariableAttributeName> DeprecatedAttribute = new GccAttribute<>(deprecated);
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor {
@NotNull private static final GccAttribute<GccVariableAttributeName> DeprecatedAttribute = new GccAttribute<>(deprecated);
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull private static final GccAttribute<GccVariableAttributeName> DeprecatedAttribute = new GccAttribute<>(deprecated); @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); private DeprecatedFieldAttributesProcessor() { } @Override
// Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/DeprecatedFieldAttributesProcessor.java import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.deprecated; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class DeprecatedFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull private static final GccAttribute<GccVariableAttributeName> DeprecatedAttribute = new GccAttribute<>(deprecated); @NotNull public static final FieldAttributesProcessor Deprecated = new DeprecatedFieldAttributesProcessor(); private DeprecatedFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override
public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final ThreadLocalModel threadLocalModel = field.getAnnotation(ThreadLocalModel.class); if (threadLocalModel == null) { return; } if (field.getModifiers().contains(FINAL)) { throw newConversionException(field, "may not be defined @ThreadLocalModel because it is static and final"); }
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final ThreadLocalModel threadLocalModel = field.getAnnotation(ThreadLocalModel.class); if (threadLocalModel == null) { return; } if (field.getModifiers().contains(FINAL)) { throw newConversionException(field, "may not be defined @ThreadLocalModel because it is static and final"); }
@Nullable final TlsModel tlsModel = threadLocalModel.value();
raphaelcohn/java2c
source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // }
import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL;
package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final ThreadLocalModel threadLocalModel = field.getAnnotation(ThreadLocalModel.class); if (threadLocalModel == null) { return; } if (field.getModifiers().contains(FINAL)) { throw newConversionException(field, "may not be defined @ThreadLocalModel because it is static and final"); } @Nullable final TlsModel tlsModel = threadLocalModel.value(); if (tlsModel == null) { return; }
// Path: source/model/com/stormmq/java2c/model/variables/TlsModel.java // public enum TlsModel // { // global_dynamic, // local_dynamic, // initial_exec, // local_exec, // ; // // @NotNull public final String tlsModelSpecifier; // // TlsModel() // { // tlsModelSpecifier = name().replace('_', '-'); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttribute.java // public final class GccAttribute<N extends Enum<N> & AttributeName> implements Writable // { // @NotNull private final N name; // @NotNull private final GccAttributeParameter[] gccAttributeParameters; // // public GccAttribute(@NotNull final N name, @NotNull GccAttributeParameter... gccAttributeParameters) // { // this.name = name; // this.gccAttributeParameters = gccAttributeParameters; // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(name.name()); // if (gccAttributeParameters.length != 0) // { // writer.write(" ("); // boolean afterFirst = false; // for (GccAttributeParameter gccAttributeParameter : gccAttributeParameters) // { // if (afterFirst) // { // writer.write(", "); // } // else // { // afterFirst = true; // } // gccAttributeParameter.write(writer); // } // writer.write(')'); // } // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/GccAttributeParameter.java // public final class GccAttributeParameter implements Writable // { // @NotNull private final String value; // // public GccAttributeParameter(@NotNull final String value) // { // this.value = '"' + value + '"'; // } // // public GccAttributeParameter(final int value) // { // assert value >= 0; // this.value = Integer.toString(value); // } // // public void write(@NotNull final Writer writer) throws IOException // { // writer.write(value); // } // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/c/gccAttributes/variable/GccVariableAttributeName.java // public enum GccVariableAttributeName implements AttributeName // { // aligned, // cleanup, // common, // nocommon, // deprecated, // mode, // packed, // section, // tls_model, // unused, // used, // vector_size, // weak, // ; // } // // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/ConversionException.java // public final class ConversionException extends Exception // { // public ConversionException(@NotNull final String message) // { // super(message); // } // // public ConversionException(@NotNull final String message, @NotNull final Exception cause) // { // super(message, cause); // } // } // Path: source/transpiler/com/stormmq/java2c/transpiler/conversion/elementConverters/fieldAttributesProcessors/ThreadLocalModelFieldAttributesProcessor.java import com.stormmq.java2c.model.variables.ThreadLocalModel; import com.stormmq.java2c.model.variables.TlsModel; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttribute; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.GccAttributeParameter; import com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName; import com.stormmq.java2c.transpiler.conversion.elementConverters.ConversionException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.lang.model.element.VariableElement; import java.util.Collection; import static com.stormmq.java2c.transpiler.conversion.c.gccAttributes.variable.GccVariableAttributeName.tls_model; import static javax.lang.model.element.Modifier.FINAL; package com.stormmq.java2c.transpiler.conversion.elementConverters.fieldAttributesProcessors; public final class ThreadLocalModelFieldAttributesProcessor extends AbstractFieldAttributesProcessor { @NotNull public static final FieldAttributesProcessor ThreadLocalModel = new ThreadLocalModelFieldAttributesProcessor(); private ThreadLocalModelFieldAttributesProcessor() { } @Override public void processField(@NotNull final Collection<GccAttribute<GccVariableAttributeName>> gccAttributes, @NotNull final VariableElement field) throws ConversionException { @Nullable final ThreadLocalModel threadLocalModel = field.getAnnotation(ThreadLocalModel.class); if (threadLocalModel == null) { return; } if (field.getModifiers().contains(FINAL)) { throw newConversionException(field, "may not be defined @ThreadLocalModel because it is static and final"); } @Nullable final TlsModel tlsModel = threadLocalModel.value(); if (tlsModel == null) { return; }
gccAttributes.add(new GccAttribute<>(tls_model, new GccAttributeParameter(tlsModel.tlsModelSpecifier)));
amitdev/PMD-Intellij
src/main/java/com/intellij/plugins/bodhi/pmd/tree/PMDLeafNode.java
// Path: src/main/java/com/intellij/plugins/bodhi/pmd/core/HasPositionInFile.java // public interface HasPositionInFile { // /** // * Returns the file name. // * @return the file name. // */ // String getFilename(); // // /** // * Returns the begin line of the position. // * @return the begin line of the position. // */ // int getBeginLine(); // // /** // * Returns the begin column of the position. // * @return the begin column of the position. // */ // int getBeginColumn(); // }
import com.intellij.plugins.bodhi.pmd.core.HasPositionInFile;
package com.intellij.plugins.bodhi.pmd.tree; /** * Abstract base class for PMD Leaf Tree Nodes. * Contains a finding: violation, suppressed violation or processing error. * This has a location in a file and the containing node is navigatable. * * @author jborgers */ public abstract class PMDLeafNode extends BasePMDNode { public boolean canNavigate() { return true; } public boolean canNavigateToSource() { return true; } @Override public int getViolationCount() { return 0; } @Override public int getSuppressedCount() { return 0; } @Override public int getErrorCount() { return 0; } /** * Open editor and select/navigate to the correct line and column in the file. * * @param finding The violation, suppressed violation or processing error. */
// Path: src/main/java/com/intellij/plugins/bodhi/pmd/core/HasPositionInFile.java // public interface HasPositionInFile { // /** // * Returns the file name. // * @return the file name. // */ // String getFilename(); // // /** // * Returns the begin line of the position. // * @return the begin line of the position. // */ // int getBeginLine(); // // /** // * Returns the begin column of the position. // * @return the begin column of the position. // */ // int getBeginColumn(); // } // Path: src/main/java/com/intellij/plugins/bodhi/pmd/tree/PMDLeafNode.java import com.intellij.plugins.bodhi.pmd.core.HasPositionInFile; package com.intellij.plugins.bodhi.pmd.tree; /** * Abstract base class for PMD Leaf Tree Nodes. * Contains a finding: violation, suppressed violation or processing error. * This has a location in a file and the containing node is navigatable. * * @author jborgers */ public abstract class PMDLeafNode extends BasePMDNode { public boolean canNavigate() { return true; } public boolean canNavigateToSource() { return true; } @Override public int getViolationCount() { return 0; } @Override public int getSuppressedCount() { return 0; } @Override public int getErrorCount() { return 0; } /** * Open editor and select/navigate to the correct line and column in the file. * * @param finding The violation, suppressed violation or processing error. */
protected void highlightFindingInEditor(HasPositionInFile finding) {
amitdev/PMD-Intellij
src/main/java/com/intellij/plugins/bodhi/pmd/tree/PMDCellRenderer.java
// Path: src/main/java/com/intellij/plugins/bodhi/pmd/core/PMDViolation.java // public class PMDViolation implements HasPositionInFile { // // private final RuleViolation ruleViolation; // private final String positionText; // private final String classAndMethodMsg; // private final String packageMsg; // // /** // * Creates a PMDViolation which wraps the IRuleViolation given. // * // * @param violation the violation // */ // public PMDViolation(RuleViolation violation) { // this.ruleViolation = violation; // this.positionText = "(" + violation.getBeginLine() + ", " + violation.getBeginColumn() + ") "; // String fileName = violation.getFilename(); // int startIndex = fileName.lastIndexOf(File.separatorChar); // String className = violation.getClassName(); // if (className == null || className.length() == 0) { // if (startIndex != -1) { // className = fileName.substring(startIndex + 1, fileName.indexOf('.', startIndex)); // } // } // String methodName = violation.getMethodName(); // if (methodName == null) { // methodName = ""; // } // if (methodName.length() > 0) { // methodName = "." + methodName + "()"; // } // String packageName = violation.getPackageName(); // this.packageMsg = (packageName != null && packageName.trim().length() > 0) ? (" in " + packageName) : ""; // this.classAndMethodMsg = className + methodName; // } // // @Override // public String getFilename() { // return ruleViolation.getFilename(); // } // // @Override // public int getBeginLine() { // return ruleViolation.getBeginLine(); // } // // @Override // public int getBeginColumn() { // return ruleViolation.getBeginColumn(); // } // // public int getEndLine() { // return ruleViolation.getEndLine(); // } // // public int getEndColumn() { // return ruleViolation.getEndColumn(); // } // // private Rule getRule() { // return ruleViolation.getRule(); // } // // public String getDescription() { // return ruleViolation.getDescription(); // } // // public String getPackageName() { // return ruleViolation.getPackageName(); // } // // public String getMethodName() { // return ruleViolation.getMethodName(); // } // // public String getClassName() { // return ruleViolation.getClassName(); // } // // public boolean isSuppressed() { // return ruleViolation.isSuppressed(); // } // // public String getVariableName() { // return ruleViolation.getVariableName(); // } // // public String getPositionText() { // return this.positionText; // } // // public String getExternalUrl() { // return getRule().getExternalInfoUrl(); // } // // public String getClassAndMethodMsg() { // return classAndMethodMsg; // } // // public String getPackageMsg() { // return packageMsg; // } // // public String getToolTip() { // return getDescription(); // } // // public String getRuleName() { // return getRule().getName(); // } // // public String getRulePriorityName() { // return getRule().getPriority().getName(); // } // // public String toString() { // return getPackageName() + "." + getClassName() + "." + getMethodName() + " at (" + getBeginLine() + "," + getBeginColumn() + ")"; // } // }
import com.intellij.openapi.util.IconLoader; import com.intellij.plugins.bodhi.pmd.core.PMDViolation; import com.intellij.ui.ColoredTreeCellRenderer; import javax.swing.*; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.intellij.plugins.bodhi.pmd.tree; /** * A Custom Cell renderer that will render the user objects of this plugin * correctly. It extends the ColoredTreeCellRenderer to make use of the text * attributes. * * @author bodhi * @version 1.2 */ public class PMDCellRenderer extends ColoredTreeCellRenderer { //Default tree icons static Icon CLOSED_ICON; static Icon OPEN_ICON; public static final Icon ERROR = IconLoader.getIcon("/compiler/error.png"); public static final Icon WARN = IconLoader.getIcon("/compiler/warning.png"); public static final Icon INFO = IconLoader.getIcon("/compiler/information.png"); private static final Map<String, Icon> prioToIcon; //Try to load idea specific icons for the tree. static { CLOSED_ICON = IconLoader.getIcon("/nodes/TreeClosed.png"); OPEN_ICON = IconLoader.getIcon("/nodes/TreeOpen.png"); Map<String, Icon> attrs = new HashMap<>(); attrs.put("Medium", WARN); attrs.put("Medium High", WARN); attrs.put("High", ERROR); attrs.put("Medium Low", INFO); attrs.put("Low", INFO); prioToIcon = Collections.unmodifiableMap(attrs); } public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof BasePMDNode) { ((BasePMDNode)value).render(this, expanded); } }
// Path: src/main/java/com/intellij/plugins/bodhi/pmd/core/PMDViolation.java // public class PMDViolation implements HasPositionInFile { // // private final RuleViolation ruleViolation; // private final String positionText; // private final String classAndMethodMsg; // private final String packageMsg; // // /** // * Creates a PMDViolation which wraps the IRuleViolation given. // * // * @param violation the violation // */ // public PMDViolation(RuleViolation violation) { // this.ruleViolation = violation; // this.positionText = "(" + violation.getBeginLine() + ", " + violation.getBeginColumn() + ") "; // String fileName = violation.getFilename(); // int startIndex = fileName.lastIndexOf(File.separatorChar); // String className = violation.getClassName(); // if (className == null || className.length() == 0) { // if (startIndex != -1) { // className = fileName.substring(startIndex + 1, fileName.indexOf('.', startIndex)); // } // } // String methodName = violation.getMethodName(); // if (methodName == null) { // methodName = ""; // } // if (methodName.length() > 0) { // methodName = "." + methodName + "()"; // } // String packageName = violation.getPackageName(); // this.packageMsg = (packageName != null && packageName.trim().length() > 0) ? (" in " + packageName) : ""; // this.classAndMethodMsg = className + methodName; // } // // @Override // public String getFilename() { // return ruleViolation.getFilename(); // } // // @Override // public int getBeginLine() { // return ruleViolation.getBeginLine(); // } // // @Override // public int getBeginColumn() { // return ruleViolation.getBeginColumn(); // } // // public int getEndLine() { // return ruleViolation.getEndLine(); // } // // public int getEndColumn() { // return ruleViolation.getEndColumn(); // } // // private Rule getRule() { // return ruleViolation.getRule(); // } // // public String getDescription() { // return ruleViolation.getDescription(); // } // // public String getPackageName() { // return ruleViolation.getPackageName(); // } // // public String getMethodName() { // return ruleViolation.getMethodName(); // } // // public String getClassName() { // return ruleViolation.getClassName(); // } // // public boolean isSuppressed() { // return ruleViolation.isSuppressed(); // } // // public String getVariableName() { // return ruleViolation.getVariableName(); // } // // public String getPositionText() { // return this.positionText; // } // // public String getExternalUrl() { // return getRule().getExternalInfoUrl(); // } // // public String getClassAndMethodMsg() { // return classAndMethodMsg; // } // // public String getPackageMsg() { // return packageMsg; // } // // public String getToolTip() { // return getDescription(); // } // // public String getRuleName() { // return getRule().getName(); // } // // public String getRulePriorityName() { // return getRule().getPriority().getName(); // } // // public String toString() { // return getPackageName() + "." + getClassName() + "." + getMethodName() + " at (" + getBeginLine() + "," + getBeginColumn() + ")"; // } // } // Path: src/main/java/com/intellij/plugins/bodhi/pmd/tree/PMDCellRenderer.java import com.intellij.openapi.util.IconLoader; import com.intellij.plugins.bodhi.pmd.core.PMDViolation; import com.intellij.ui.ColoredTreeCellRenderer; import javax.swing.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.intellij.plugins.bodhi.pmd.tree; /** * A Custom Cell renderer that will render the user objects of this plugin * correctly. It extends the ColoredTreeCellRenderer to make use of the text * attributes. * * @author bodhi * @version 1.2 */ public class PMDCellRenderer extends ColoredTreeCellRenderer { //Default tree icons static Icon CLOSED_ICON; static Icon OPEN_ICON; public static final Icon ERROR = IconLoader.getIcon("/compiler/error.png"); public static final Icon WARN = IconLoader.getIcon("/compiler/warning.png"); public static final Icon INFO = IconLoader.getIcon("/compiler/information.png"); private static final Map<String, Icon> prioToIcon; //Try to load idea specific icons for the tree. static { CLOSED_ICON = IconLoader.getIcon("/nodes/TreeClosed.png"); OPEN_ICON = IconLoader.getIcon("/nodes/TreeOpen.png"); Map<String, Icon> attrs = new HashMap<>(); attrs.put("Medium", WARN); attrs.put("Medium High", WARN); attrs.put("High", ERROR); attrs.put("Medium Low", INFO); attrs.put("Low", INFO); prioToIcon = Collections.unmodifiableMap(attrs); } public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof BasePMDNode) { ((BasePMDNode)value).render(this, expanded); } }
public void setIconForViolationPrio(PMDViolation violation) {
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/recording/CallRecordingSupplier.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodNameMatcher.java // public final class MethodNameMatcher implements MethodCallPredicate { // private final String methodName; // private final Class<?> targetClass; // // public MethodNameMatcher(String methodName, Class<?> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(targetClass) && methodCall.name().equals(methodName); // } // }
import com.google.common.base.Function; import com.google.common.base.Supplier; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodNameMatcher;
package com.timgroup.stanislavski.recording; public final class CallRecordingSupplier { private CallRecordingSupplier() { } public static <I, R> I proxying(final Class<I> interfaceType,
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodNameMatcher.java // public final class MethodNameMatcher implements MethodCallPredicate { // private final String methodName; // private final Class<?> targetClass; // // public MethodNameMatcher(String methodName, Class<?> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(targetClass) && methodCall.name().equals(methodName); // } // } // Path: src/main/java/com/timgroup/stanislavski/recording/CallRecordingSupplier.java import com.google.common.base.Function; import com.google.common.base.Supplier; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodNameMatcher; package com.timgroup.stanislavski.recording; public final class CallRecordingSupplier { private CallRecordingSupplier() { } public static <I, R> I proxying(final Class<I> interfaceType,
Function<Iterable<MethodCall>, R> interpreter) {
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/recording/CallRecordingSupplier.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodNameMatcher.java // public final class MethodNameMatcher implements MethodCallPredicate { // private final String methodName; // private final Class<?> targetClass; // // public MethodNameMatcher(String methodName, Class<?> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(targetClass) && methodCall.name().equals(methodName); // } // }
import com.google.common.base.Function; import com.google.common.base.Supplier; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodNameMatcher;
package com.timgroup.stanislavski.recording; public final class CallRecordingSupplier { private CallRecordingSupplier() { } public static <I, R> I proxying(final Class<I> interfaceType, Function<Iterable<MethodCall>, R> interpreter) { return InterceptingMethodCallRecorder.proxying(interfaceType,
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodNameMatcher.java // public final class MethodNameMatcher implements MethodCallPredicate { // private final String methodName; // private final Class<?> targetClass; // // public MethodNameMatcher(String methodName, Class<?> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(targetClass) && methodCall.name().equals(methodName); // } // } // Path: src/main/java/com/timgroup/stanislavski/recording/CallRecordingSupplier.java import com.google.common.base.Function; import com.google.common.base.Supplier; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodNameMatcher; package com.timgroup.stanislavski.recording; public final class CallRecordingSupplier { private CallRecordingSupplier() { } public static <I, R> I proxying(final Class<I> interfaceType, Function<Iterable<MethodCall>, R> interpreter) { return InterceptingMethodCallRecorder.proxying(interfaceType,
new MethodNameMatcher("get", Supplier.class),
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/interpreters/InterpretersTest.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.Method; import java.util.List; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import com.timgroup.stanislavski.reflection.MethodCall; import static org.hamcrest.MatcherAssert.assertThat;
package com.timgroup.stanislavski.interpreters; public class InterpretersTest { private Function<String, String> toUpperCase() { return new Function<String, String>() { @Override public String apply(String arg0) { return arg0.toUpperCase(); } }; } public static interface TestInterface { public TestInterface foo(String value); @AddressesProperty("quux") public TestInterface baz(String value); } @Test public void constructs_a_name_value_interpreter_using_supplied_key_and_value_interpreters() throws SecurityException, NoSuchMethodException { KeyValuePairInterpreter<String, String> interpreter = Interpreters.keyValuePairInterpreter(ExtractorFor.theMethodName() .compose(toUpperCase()) .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class))) .obtainingValueWith(ExtractorFor.theFirstArgument() .compose(Functions.toStringFunction()));
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/test/java/com/timgroup/stanislavski/interpreters/InterpretersTest.java import java.lang.reflect.Method; import java.util.List; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import com.timgroup.stanislavski.reflection.MethodCall; import static org.hamcrest.MatcherAssert.assertThat; package com.timgroup.stanislavski.interpreters; public class InterpretersTest { private Function<String, String> toUpperCase() { return new Function<String, String>() { @Override public String apply(String arg0) { return arg0.toUpperCase(); } }; } public static interface TestInterface { public TestInterface foo(String value); @AddressesProperty("quux") public TestInterface baz(String value); } @Test public void constructs_a_name_value_interpreter_using_supplied_key_and_value_interpreters() throws SecurityException, NoSuchMethodException { KeyValuePairInterpreter<String, String> interpreter = Interpreters.keyValuePairInterpreter(ExtractorFor.theMethodName() .compose(toUpperCase()) .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class))) .obtainingValueWith(ExtractorFor.theFirstArgument() .compose(Functions.toStringFunction()));
List<MethodCall> callHistory = Lists.newArrayList(
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/matchers/MatchesWith.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.hamcrest.Matcher; import com.google.common.base.Function; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic.matchers; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MatchesWith {
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MatchesWith.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.hamcrest.Matcher; import com.google.common.base.Function; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic.matchers; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MatchesWith {
Class<? extends Function<MethodCall, Matcher<?>>> value();
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/builders/BuilderFactory.java
// Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.Method; import com.google.common.base.Supplier; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic.builders; public class BuilderFactory<I extends Supplier<T>, T> implements Supplier<I> { private final Class<T> recordType; private final Class<I> interfaceClass; public static <I extends Supplier<T>, T> BuilderFactoryMaker<I, T> validating(Class<I> interfaceClass) { return new BuilderFactoryMaker<I, T>(interfaceClass); } public static class BuilderFactoryMaker<I extends Supplier<T>, T> { private final Class<I> interfaceClass; private BuilderFactoryMaker(Class<I> interfaceClass) { this.interfaceClass = interfaceClass; } public BuilderFactory<I, T> against(Class<T> recordType) { ReflectiveAccessorFactory<T> factory = ReflectiveAccessorFactory.forClass(recordType); for (Method method : interfaceClass.getDeclaredMethods()) {
// Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/builders/BuilderFactory.java import java.lang.reflect.Method; import com.google.common.base.Supplier; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic.builders; public class BuilderFactory<I extends Supplier<T>, T> implements Supplier<I> { private final Class<T> recordType; private final Class<I> interfaceClass; public static <I extends Supplier<T>, T> BuilderFactoryMaker<I, T> validating(Class<I> interfaceClass) { return new BuilderFactoryMaker<I, T>(interfaceClass); } public static class BuilderFactoryMaker<I extends Supplier<T>, T> { private final Class<I> interfaceClass; private BuilderFactoryMaker(Class<I> interfaceClass) { this.interfaceClass = interfaceClass; } public BuilderFactory<I, T> against(Class<T> recordType) { ReflectiveAccessorFactory<T> factory = ReflectiveAccessorFactory.forClass(recordType); for (Method method : interfaceClass.getDeclaredMethods()) {
MethodCall methodCall = MethodCall.create(method);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/builders/BuilderFactory.java
// Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.Method; import com.google.common.base.Supplier; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic.builders; public class BuilderFactory<I extends Supplier<T>, T> implements Supplier<I> { private final Class<T> recordType; private final Class<I> interfaceClass; public static <I extends Supplier<T>, T> BuilderFactoryMaker<I, T> validating(Class<I> interfaceClass) { return new BuilderFactoryMaker<I, T>(interfaceClass); } public static class BuilderFactoryMaker<I extends Supplier<T>, T> { private final Class<I> interfaceClass; private BuilderFactoryMaker(Class<I> interfaceClass) { this.interfaceClass = interfaceClass; } public BuilderFactory<I, T> against(Class<T> recordType) { ReflectiveAccessorFactory<T> factory = ReflectiveAccessorFactory.forClass(recordType); for (Method method : interfaceClass.getDeclaredMethods()) { MethodCall methodCall = MethodCall.create(method);
// Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/builders/BuilderFactory.java import java.lang.reflect.Method; import com.google.common.base.Supplier; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic.builders; public class BuilderFactory<I extends Supplier<T>, T> implements Supplier<I> { private final Class<T> recordType; private final Class<I> interfaceClass; public static <I extends Supplier<T>, T> BuilderFactoryMaker<I, T> validating(Class<I> interfaceClass) { return new BuilderFactoryMaker<I, T>(interfaceClass); } public static class BuilderFactoryMaker<I extends Supplier<T>, T> { private final Class<I> interfaceClass; private BuilderFactoryMaker(Class<I> interfaceClass) { this.interfaceClass = interfaceClass; } public BuilderFactory<I, T> against(Class<T> recordType) { ReflectiveAccessorFactory<T> factory = ReflectiveAccessorFactory.forClass(recordType); for (Method method : interfaceClass.getDeclaredMethods()) { MethodCall methodCall = MethodCall.create(method);
String propertyName = MethodNameToPropertyNameTranslator.interpret(methodCall);
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/magic/builders/MagicViewRecordBuilderTest.java
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // }
import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package com.timgroup.stanislavski.magic.builders; public class MagicViewRecordBuilderTest { public static interface ViewRecord { BuilderFactory<Builder, ViewRecord> factory = BuilderFactory.validating(Builder.class).against(ViewRecord.class); String getName(); int getAge(); String favouriteColour(); String quest(); public static interface Builder extends Supplier<ViewRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); } } public static interface RecordMatcher extends Matcher<ViewRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // } // Path: src/test/java/com/timgroup/stanislavski/magic/builders/MagicViewRecordBuilderTest.java import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package com.timgroup.stanislavski.magic.builders; public class MagicViewRecordBuilderTest { public static interface ViewRecord { BuilderFactory<Builder, ViewRecord> factory = BuilderFactory.validating(Builder.class).against(ViewRecord.class); String getName(); int getAge(); String favouriteColour(); String quest(); public static interface Builder extends Supplier<ViewRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); } } public static interface RecordMatcher extends Matcher<ViewRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
return MagicJavaBeanMatcher.matching(ViewRecord.class).using(RecordMatcher.class);
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/magic/builders/MagicImmutableRecordBuilderTest.java
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // }
import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
this.favouriteColour = favouriteColour; this.quest = quest; } public static interface Builder extends Supplier<ImmutableRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(Quest quest); @AddressesProperty("quest") Builder havingTheNobleQuest(Supplier<Quest> quest); } public static Builder builder() { return MagicRecordBuilder.building(ImmutableRecord.class).using(ImmutableRecord.Builder.class); } } public static interface QuestMatcher extends Matcher<Quest> { @AddressesProperty("object") QuestMatcher for_the(String object); @AddressesProperty("declaration") QuestMatcher declaring(String declaration); } public QuestMatcher the_quest() {
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // } // Path: src/test/java/com/timgroup/stanislavski/magic/builders/MagicImmutableRecordBuilderTest.java import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; this.favouriteColour = favouriteColour; this.quest = quest; } public static interface Builder extends Supplier<ImmutableRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(Quest quest); @AddressesProperty("quest") Builder havingTheNobleQuest(Supplier<Quest> quest); } public static Builder builder() { return MagicRecordBuilder.building(ImmutableRecord.class).using(ImmutableRecord.Builder.class); } } public static interface QuestMatcher extends Matcher<Quest> { @AddressesProperty("object") QuestMatcher for_the(String object); @AddressesProperty("declaration") QuestMatcher declaring(String declaration); } public QuestMatcher the_quest() {
return MagicJavaBeanMatcher.matching(Quest.class).using(QuestMatcher.class);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/interpreters/Interpreters.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import com.google.common.base.Function; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.interpreters; public final class Interpreters { private Interpreters() { } public static final class KeyValuePairInterpreterBuilder<K> {
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/interpreters/Interpreters.java import com.google.common.base.Function; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.interpreters; public final class Interpreters { private Interpreters() { } public static final class KeyValuePairInterpreterBuilder<K> {
private final Function<MethodCall, K> keyInterpreter;
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/matchers/AMethodCall.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCallArgument.java // public final class MethodCallArgument<F> { // // public static final Function<MethodCallArgument<?>, Object> TO_VALUE = // new Function<MethodCallArgument<?>, Object>() { // @Override public Object apply(MethodCallArgument<?> arg0) { // return arg0.value(); // } // }; // // public static List<MethodCallArgument<?>> wrapArguments(Method method, Object[] args) { // if (args == null) { // return Collections.emptyList(); // } // Builder<MethodCallArgument<?>> builder = ImmutableList.builder(); // Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // for (int i=0; i<args.length; i++) { // MethodCallArgument<?> argument = create(args[i], parameterAnnotations[i]); // builder.add(argument); // } // return builder.build(); // } // // private final F value; // private final Class<F> type; // private List<Annotation> parameterAnnotations; // // @SuppressWarnings("unchecked") // public static <F> MethodCallArgument<F> create(F argument, Annotation...parameterAnnotations) { // List<Annotation> parameterAnnotationList = Lists.newArrayList(parameterAnnotations); // return new MethodCallArgument<F>(argument, argument == null ? null : (Class<F>) argument.getClass(), parameterAnnotationList); // } // // private MethodCallArgument(F value, Class<F> type, List<Annotation> parameterAnnotations) { // this.value = value; // this.type = type; // this.parameterAnnotations = parameterAnnotations; // } // // public Class<F> type() { // return type; // } // // public F value() { // return value; // } // // public List<Annotation> parameterAnnotations() { // return parameterAnnotations; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return Iterables.any(parameterAnnotations, Predicates.instanceOf(annotationClass)); // } // // @SuppressWarnings("unchecked") // public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { // return (A) Iterables.find(parameterAnnotations, Predicates.instanceOf(annotationClass)); // } // // @Override public String toString() { // return String.format("A %s of %s, annotated with %s", type, value, parameterAnnotations); // } // }
import java.util.Collection; import java.util.Iterator; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import com.google.common.collect.Lists; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodCallArgument;
} public AMethodCall<C> and(AnArgument<?> anArgument) { arguments.add(anArgument); return this; } @Override public void describeTo(Description description) { description.appendText(" a method call to the method ").appendValue(methodName).appendText(" on class ").appendValue(targetClass); if (arguments.size() > 0) { description.appendText(" with arguments ").appendValueList("[", ",", "]", arguments); } } @Override protected boolean matchesSafely(MethodCall item, Description mismatchDescription) { if (!item.targetClass().equals(targetClass)) { mismatchDescription.appendText(" the target class was ").appendValue(targetClass); return false; } if (!item.name().equals(methodName)) { mismatchDescription.appendText(" the method called was ").appendText(methodName); return false; } if (arguments.size() != item.arguments().size()) { mismatchDescription.appendText(" the number of arguments was ").appendValue(item.arguments().size()); return false; } Iterator<AnArgument<?>> matcherIterator = arguments.iterator();
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCallArgument.java // public final class MethodCallArgument<F> { // // public static final Function<MethodCallArgument<?>, Object> TO_VALUE = // new Function<MethodCallArgument<?>, Object>() { // @Override public Object apply(MethodCallArgument<?> arg0) { // return arg0.value(); // } // }; // // public static List<MethodCallArgument<?>> wrapArguments(Method method, Object[] args) { // if (args == null) { // return Collections.emptyList(); // } // Builder<MethodCallArgument<?>> builder = ImmutableList.builder(); // Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // for (int i=0; i<args.length; i++) { // MethodCallArgument<?> argument = create(args[i], parameterAnnotations[i]); // builder.add(argument); // } // return builder.build(); // } // // private final F value; // private final Class<F> type; // private List<Annotation> parameterAnnotations; // // @SuppressWarnings("unchecked") // public static <F> MethodCallArgument<F> create(F argument, Annotation...parameterAnnotations) { // List<Annotation> parameterAnnotationList = Lists.newArrayList(parameterAnnotations); // return new MethodCallArgument<F>(argument, argument == null ? null : (Class<F>) argument.getClass(), parameterAnnotationList); // } // // private MethodCallArgument(F value, Class<F> type, List<Annotation> parameterAnnotations) { // this.value = value; // this.type = type; // this.parameterAnnotations = parameterAnnotations; // } // // public Class<F> type() { // return type; // } // // public F value() { // return value; // } // // public List<Annotation> parameterAnnotations() { // return parameterAnnotations; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return Iterables.any(parameterAnnotations, Predicates.instanceOf(annotationClass)); // } // // @SuppressWarnings("unchecked") // public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { // return (A) Iterables.find(parameterAnnotations, Predicates.instanceOf(annotationClass)); // } // // @Override public String toString() { // return String.format("A %s of %s, annotated with %s", type, value, parameterAnnotations); // } // } // Path: src/test/java/com/timgroup/stanislavski/matchers/AMethodCall.java import java.util.Collection; import java.util.Iterator; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import com.google.common.collect.Lists; import com.timgroup.stanislavski.reflection.MethodCall; import com.timgroup.stanislavski.reflection.MethodCallArgument; } public AMethodCall<C> and(AnArgument<?> anArgument) { arguments.add(anArgument); return this; } @Override public void describeTo(Description description) { description.appendText(" a method call to the method ").appendValue(methodName).appendText(" on class ").appendValue(targetClass); if (arguments.size() > 0) { description.appendText(" with arguments ").appendValueList("[", ",", "]", arguments); } } @Override protected boolean matchesSafely(MethodCall item, Description mismatchDescription) { if (!item.targetClass().equals(targetClass)) { mismatchDescription.appendText(" the target class was ").appendValue(targetClass); return false; } if (!item.name().equals(methodName)) { mismatchDescription.appendText(" the method called was ").appendText(methodName); return false; } if (arguments.size() != item.arguments().size()) { mismatchDescription.appendText(" the number of arguments was ").appendValue(item.arguments().size()); return false; } Iterator<AnArgument<?>> matcherIterator = arguments.iterator();
Iterator<MethodCallArgument<?>> argumentIterator = item.arguments().iterator();
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.proxying; public class InvocationHandlerAdapter implements InvocationHandler { private final MethodCallHandler handler; public InvocationHandlerAdapter(MethodCallHandler handler) { this.handler = handler; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("equals".equals(method.getName())) { return proxy == args[0]; } if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); }
// Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.proxying; public class InvocationHandlerAdapter implements InvocationHandler { private final MethodCallHandler handler; public InvocationHandlerAdapter(MethodCallHandler handler) { this.handler = handler; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("equals".equals(method.getName())) { return proxy == args[0]; } if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); }
MethodCall methodCall = MethodCall.create(method, args);
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/magic/builders/MagicBeanRecordBuilderTest.java
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // }
import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
} public static interface Builder extends Supplier<BeanRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); } public static Builder builder() { return MagicRecordBuilder.building(BeanRecord.class).using(Builder.class); } } public static interface RecordMatcher extends Matcher<BeanRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // } // Path: src/test/java/com/timgroup/stanislavski/magic/builders/MagicBeanRecordBuilderTest.java import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; } public static interface Builder extends Supplier<BeanRecord> { Builder withName(String name); Builder withAge(Integer age); Builder withFavouriteColour(String favouriteColour); Builder with_name(String name); Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); } public static Builder builder() { return MagicRecordBuilder.building(BeanRecord.class).using(Builder.class); } } public static interface RecordMatcher extends Matcher<BeanRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
return MagicJavaBeanMatcher.matching(BeanRecord.class).using(RecordMatcher.class);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/recording/RecordingMethodCallHandler.java
// Path: src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java // public class InvocationHandlerAdapter implements InvocationHandler { // // private final MethodCallHandler handler; // // public InvocationHandlerAdapter(MethodCallHandler handler) { // this.handler = handler; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if ("equals".equals(method.getName())) { // return proxy == args[0]; // } // if (Object.class.equals(method.getDeclaringClass())) { // return method.invoke(this, args); // } // MethodCall methodCall = MethodCall.create(method, args); // return handler.handle(methodCall); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.timgroup.stanislavski.proxying.InvocationHandlerAdapter; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.recording; public final class RecordingMethodCallHandler implements MethodCallHandler { private final MethodCallRecorder recorder = new MethodCallRecorder();
// Path: src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java // public class InvocationHandlerAdapter implements InvocationHandler { // // private final MethodCallHandler handler; // // public InvocationHandlerAdapter(MethodCallHandler handler) { // this.handler = handler; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if ("equals".equals(method.getName())) { // return proxy == args[0]; // } // if (Object.class.equals(method.getDeclaringClass())) { // return method.invoke(this, args); // } // MethodCall methodCall = MethodCall.create(method, args); // return handler.handle(methodCall); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/recording/RecordingMethodCallHandler.java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.timgroup.stanislavski.proxying.InvocationHandlerAdapter; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.recording; public final class RecordingMethodCallHandler implements MethodCallHandler { private final MethodCallRecorder recorder = new MethodCallRecorder();
private final InvocationHandler invocationHandler= new InvocationHandlerAdapter(this);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/recording/RecordingMethodCallHandler.java
// Path: src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java // public class InvocationHandlerAdapter implements InvocationHandler { // // private final MethodCallHandler handler; // // public InvocationHandlerAdapter(MethodCallHandler handler) { // this.handler = handler; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if ("equals".equals(method.getName())) { // return proxy == args[0]; // } // if (Object.class.equals(method.getDeclaringClass())) { // return method.invoke(this, args); // } // MethodCall methodCall = MethodCall.create(method, args); // return handler.handle(methodCall); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.timgroup.stanislavski.proxying.InvocationHandlerAdapter; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.recording; public final class RecordingMethodCallHandler implements MethodCallHandler { private final MethodCallRecorder recorder = new MethodCallRecorder(); private final InvocationHandler invocationHandler= new InvocationHandlerAdapter(this); @SuppressWarnings("unchecked") public <I> I getProxy(Class<I> interfaceType) { return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[] { interfaceType }, invocationHandler); }
// Path: src/main/java/com/timgroup/stanislavski/proxying/InvocationHandlerAdapter.java // public class InvocationHandlerAdapter implements InvocationHandler { // // private final MethodCallHandler handler; // // public InvocationHandlerAdapter(MethodCallHandler handler) { // this.handler = handler; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if ("equals".equals(method.getName())) { // return proxy == args[0]; // } // if (Object.class.equals(method.getDeclaringClass())) { // return method.invoke(this, args); // } // MethodCall methodCall = MethodCall.create(method, args); // return handler.handle(methodCall); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/recording/RecordingMethodCallHandler.java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.timgroup.stanislavski.proxying.InvocationHandlerAdapter; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.recording; public final class RecordingMethodCallHandler implements MethodCallHandler { private final MethodCallRecorder recorder = new MethodCallRecorder(); private final InvocationHandler invocationHandler= new InvocationHandlerAdapter(this); @SuppressWarnings("unchecked") public <I> I getProxy(Class<I> interfaceType) { return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[] { interfaceType }, invocationHandler); }
public Iterable<MethodCall> callHistory() {
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorder.java
// Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/ProxyFactory.java // public final class ProxyFactory { // // private final InvocationHandler invocationHandler; // // public static ProxyFactory forMethodCallHandler(MethodCallHandler handler) { // return new ProxyFactory(new InvocationHandlerAdapter(handler)); // } // // public ProxyFactory(InvocationHandler invocationHandler) { // this.invocationHandler = invocationHandler; // } // // @SuppressWarnings("unchecked") // public <I> I getProxy(Class<I> interfaceType) { // return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), // new Class<?>[] { interfaceType }, // invocationHandler); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import com.google.common.base.Predicate; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.proxying.ProxyFactory; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.recording; public class InterceptingMethodCallRecorder<T> implements MethodCallHandler { private final Predicate<MethodCall> finalCallMatcher; private final FinalCallHandler<T> finalCallHandler;
// Path: src/main/java/com/timgroup/stanislavski/proxying/MethodCallHandler.java // public interface MethodCallHandler { // Object handle(MethodCall methodCall); // } // // Path: src/main/java/com/timgroup/stanislavski/proxying/ProxyFactory.java // public final class ProxyFactory { // // private final InvocationHandler invocationHandler; // // public static ProxyFactory forMethodCallHandler(MethodCallHandler handler) { // return new ProxyFactory(new InvocationHandlerAdapter(handler)); // } // // public ProxyFactory(InvocationHandler invocationHandler) { // this.invocationHandler = invocationHandler; // } // // @SuppressWarnings("unchecked") // public <I> I getProxy(Class<I> interfaceType) { // return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), // new Class<?>[] { interfaceType }, // invocationHandler); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorder.java import com.google.common.base.Predicate; import com.timgroup.stanislavski.proxying.MethodCallHandler; import com.timgroup.stanislavski.proxying.ProxyFactory; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.recording; public class InterceptingMethodCallRecorder<T> implements MethodCallHandler { private final Predicate<MethodCall> finalCallMatcher; private final FinalCallHandler<T> finalCallHandler;
private final ProxyFactory proxyFactory;
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/magic/builders/MagicTypedKeywordRecordBuilderTest.java
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.karg.keywords.typed.TypedKeyword; import com.timgroup.karg.keywords.typed.TypedKeywordArguments; import com.timgroup.karg.keywords.typed.TypedKeywords; import com.timgroup.karg.valuetypes.ValueType; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher;
Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); @AddressesProperty("quest") Builder having_the_noble_quest(String quest); } public static Builder builder() { return MagicRecordBuilder.building(TypedKeywordRecord.class).using(Builder.class); } public static Builder updating(TypedKeywordRecord instance) { return MagicRecordBuilder.updating(instance).using(Builder.class); } } public static interface RecordMatcher extends Matcher<TypedKeywordRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
// Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java // public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { // private final Class<T> targetClass; // // public static class MagicJavaBeanMatcherBuilder<T> { // private Class<T> targetClass; // private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { // this.targetClass = targetClass; // } // public <I> I using(Class<I> interfaceClass) { // MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass); // return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher); // } // } // // public static <T> MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T> matching(Class<T> targetClass) { // return new MagicJavaBeanMatcher.MagicJavaBeanMatcherBuilder<T>(targetClass); // } // // private MagicJavaBeanMatcher(Class<T> targetClass) { // this.targetClass = targetClass; // } // // @Override // public Object handle(MethodCall closingCall, // Iterable<MethodCall> callHistory) { // try { // return closingCall.applyTo(makeMatcherFrom(callHistory)); // } catch (RuntimeException e) { // throw e; // } catch (Throwable e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean apply(MethodCall methodCall) { // return methodCall.targetClass().equals(Matcher.class) || methodCall.targetClass().equals(SelfDescribing.class); // } // // private Matcher<T> makeMatcherFrom(Iterable<MethodCall> callHistory) { // return new InstanceWithPropertiesMatcher<T>(targetClass, JavaBeanPropertyMatcherMaker.interpret(targetClass, callHistory)); // } // } // Path: src/test/java/com/timgroup/stanislavski/magic/builders/MagicTypedKeywordRecordBuilderTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import com.google.common.base.Supplier; import com.timgroup.karg.keywords.typed.TypedKeyword; import com.timgroup.karg.keywords.typed.TypedKeywordArguments; import com.timgroup.karg.keywords.typed.TypedKeywords; import com.timgroup.karg.valuetypes.ValueType; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.magic.matchers.MagicJavaBeanMatcher; Builder with_age(Integer age); Builder with_favourite_colour(String favouriteColour); @AddressesProperty("quest") Builder havingTheNobleQuest(String quest); @AddressesProperty("quest") Builder having_the_noble_quest(String quest); } public static Builder builder() { return MagicRecordBuilder.building(TypedKeywordRecord.class).using(Builder.class); } public static Builder updating(TypedKeywordRecord instance) { return MagicRecordBuilder.updating(instance).using(Builder.class); } } public static interface RecordMatcher extends Matcher<TypedKeywordRecord> { RecordMatcher with_name(String name); RecordMatcher with_name(Matcher<? super String> name); RecordMatcher with_age(Integer age); RecordMatcher with_favourite_colour(String favouriteColour); @AddressesProperty("quest") RecordMatcher having_the_noble_quest(String quest); } private RecordMatcher a_record() {
return MagicJavaBeanMatcher.matching(TypedKeywordRecord.class).using(RecordMatcher.class);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/matchers/JavaBeanPropertyMatcherMaker.java
// Path: src/main/java/com/timgroup/stanislavski/interpreters/MethodCallInterpreter.java // public interface MethodCallInterpreter<T> extends Function<MethodCall, T> { } // // Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import org.hamcrest.Matcher; import org.hamcrest.Matchers; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.interpreters.MethodCallInterpreter; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall;
.value() .newInstance() .apply(methodCall); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } public <V> Matcher<? super T> make(MethodCall methodCall, Matcher<? super V> matcher) { return make(getPropertyName(methodCall), matcher); } @SuppressWarnings({ "rawtypes", "unchecked" }) public <V> Matcher<? super T> make(String propertyName, Matcher<? super V> matcher) { Getter<T, V> getter = (Getter) getterProvider.apply(propertyName); return JavaBeanPropertyMatcher.matching(propertyName, getter, matcher); } @SuppressWarnings("unchecked") private <V> Matcher<? super V> getMatcher(MethodCall methodCall) { Object firstArgumentValue = methodCall.firstArgument().value(); if (firstArgumentValue instanceof Matcher) { return Matchers.is((Matcher<? super V>) firstArgumentValue); } return Matchers.is(firstArgumentValue); } private String getPropertyName(MethodCall methodCall) {
// Path: src/main/java/com/timgroup/stanislavski/interpreters/MethodCallInterpreter.java // public interface MethodCallInterpreter<T> extends Function<MethodCall, T> { } // // Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java // public class MethodNameToPropertyNameTranslator implements Function<String, String> { // // public static String interpret(MethodCall methodCall) { // return ExtractorFor.theMethodName() // .compose(new MethodNameToPropertyNameTranslator()) // .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) // .apply(methodCall); // } // // private static final List<Pattern> NO_UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with", "having", "") // .followedByOneOf("An", "A", "The", "") // .followedByOneOf("([A-Z].*)Of", "([A-Z].*)")); // // private static final List<Pattern> UNDERSCORE_PATTERNS = // Patterns.matching(One.of("with_", "having_", "") // .followedByOneOf("an_", "a_", "the_", "") // .followedByOneOf("([a-z].*)_of", "([a-z].*)")); // // @Override // public String apply(String methodName) { // if (methodName.contains("_")) { // return interpret(methodName, // UNDERSCORE_PATTERNS, // TargetNameParser.UNDERSCORE_SEPARATED); // } // // return interpret(methodName, // NO_UNDERSCORE_PATTERNS, // TargetNameParser.CAMEL_CASE); // } // // private String interpret(String methodName, // List<Pattern> patterns, // TargetNameParser parser) { // for (Pattern pattern : patterns) { // Matcher matcher = pattern.matcher(methodName); // if (matcher.matches()) { // return parser.parse(matcher.group(1)) // .formatWith(LOWER_CAMEL_CASE); // } // } // return methodName; // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/matchers/JavaBeanPropertyMatcherMaker.java import org.hamcrest.Matcher; import org.hamcrest.Matchers; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reflection.ReflectiveAccessorFactory; import com.timgroup.stanislavski.interpreters.MethodCallInterpreter; import com.timgroup.stanislavski.magic.MethodNameToPropertyNameTranslator; import com.timgroup.stanislavski.reflection.MethodCall; .value() .newInstance() .apply(methodCall); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } public <V> Matcher<? super T> make(MethodCall methodCall, Matcher<? super V> matcher) { return make(getPropertyName(methodCall), matcher); } @SuppressWarnings({ "rawtypes", "unchecked" }) public <V> Matcher<? super T> make(String propertyName, Matcher<? super V> matcher) { Getter<T, V> getter = (Getter) getterProvider.apply(propertyName); return JavaBeanPropertyMatcher.matching(propertyName, getter, matcher); } @SuppressWarnings("unchecked") private <V> Matcher<? super V> getMatcher(MethodCall methodCall) { Object firstArgumentValue = methodCall.firstArgument().value(); if (firstArgumentValue instanceof Matcher) { return Matchers.is((Matcher<? super V>) firstArgumentValue); } return Matchers.is(firstArgumentValue); } private String getPropertyName(MethodCall methodCall) {
return MethodNameToPropertyNameTranslator.interpret(methodCall);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) {
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) {
return ExtractorFor.theMethodName()
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) { return ExtractorFor.theMethodName() .compose(new MethodNameToPropertyNameTranslator())
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) { return ExtractorFor.theMethodName() .compose(new MethodNameToPropertyNameTranslator())
.chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class))
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) { return ExtractorFor.theMethodName() .compose(new MethodNameToPropertyNameTranslator()) .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) .apply(methodCall); } private static final List<Pattern> NO_UNDERSCORE_PATTERNS =
// Path: src/main/java/com/timgroup/stanislavski/interpreters/AnnotationOverride.java // public class AnnotationOverride<A extends Annotation, T> implements MethodCallInterpreter<Optional<T>> { // // public static <A extends Annotation, T> Function<MethodCall, Optional<T>> obtainingValueOf(final Class<A> annotationClass) { // return new AnnotationOverride<A, T>(annotationClass, new Function<A, T>() { // @SuppressWarnings("unchecked") // @Override public T apply(A annotation) { // try { // Method method = annotationClass.getMethod("value"); // return (T) method.invoke(annotation); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // }); // } // // private final Class<A> annotationClass; // private final Function<A, T> annotationInterpreter; // // public AnnotationOverride(Class<A> annotationClass, Function<A, T> annotationInterpreter) { // this.annotationClass = annotationClass; // this.annotationInterpreter = annotationInterpreter; // } // // @Override // public Optional<T> apply(MethodCall methodCall) { // if (!methodCall.hasAnnotation(annotationClass)) { // return Optional.absent(); // } // A annotation = methodCall.getAnnotation(annotationClass); // return Optional.of(annotationInterpreter.apply(annotation)); // } // // } // // Path: src/main/java/com/timgroup/stanislavski/interpreters/ExtractorFor.java // public final class ExtractorFor { // // public static Chainable<MethodCall, String> theMethodName() { // return Chainable.chainable(new MethodCallInterpreter<String>() { // @Override public String apply(MethodCall methodCall) { // return methodCall.name(); // } // }); // } // // public static Chainable<MethodCall, Object> theFirstArgument() { // return Chainable.chainable(new MethodCallInterpreter<Object>() { // @Override public Object apply(MethodCall methodCall) { // Preconditions.checkArgument(methodCall.arguments().size() == 1, "Incorrect number of arguments for method call %s", methodCall); // return methodCall.firstArgument().value(); // } // }); // } // } // // Path: src/main/java/com/timgroup/stanislavski/magic/Patterns.java // public static class One implements PatternGenerator { // public static Patterns.One of(String...choices) { // return new One(choices); // } // // private final List<String[]> choiceSets = Lists.newLinkedList(); // // public One(String[] choices) { // choiceSets.add(choices); // } // // public Patterns.One followedByOneOf(String...choices) { // choiceSets.add(choices); // return this; // } // // @Override public List<Pattern> generate() { // List<Pattern> patterns = Lists.newLinkedList(); // generate(0, patterns, ""); // return patterns; // } // // private void generate(int pos, List<Pattern> patterns, String prefix) { // if (pos >= choiceSets.size()) { // patterns.add(Pattern.compile(prefix)); // return; // } // // for (String choice : choiceSets.get(pos)) { // generate(pos+1, patterns, prefix + choice); // } // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/MethodNameToPropertyNameTranslator.java import static com.timgroup.karg.naming.TargetNameFormatter.LOWER_CAMEL_CASE; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Function; import com.timgroup.karg.naming.TargetNameParser; import com.timgroup.stanislavski.interpreters.AddressesProperty; import com.timgroup.stanislavski.interpreters.AnnotationOverride; import com.timgroup.stanislavski.interpreters.ExtractorFor; import com.timgroup.stanislavski.magic.Patterns.One; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic; public class MethodNameToPropertyNameTranslator implements Function<String, String> { public static String interpret(MethodCall methodCall) { return ExtractorFor.theMethodName() .compose(new MethodNameToPropertyNameTranslator()) .chain(AnnotationOverride.<AddressesProperty, String>obtainingValueOf(AddressesProperty.class)) .apply(methodCall); } private static final List<Pattern> NO_UNDERSCORE_PATTERNS =
Patterns.matching(One.of("with", "having", "")
tim-group/stanislavski
src/test/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorderTest.java
// Path: src/test/java/com/timgroup/stanislavski/matchers/AMethodCall.java // public final class AMethodCall<C> extends TypeSafeDiagnosingMatcher<MethodCall> { // private final String methodName; // private final Class<C> targetClass; // private final Collection<AnArgument<?>> arguments = Lists.newLinkedList(); // // public static interface MethodNameBinder { // <C> AMethodCall<C> of(Class<C> interfaceClass); // } // // public static AMethodCall.MethodNameBinder to(final String methodName) { // return new MethodNameBinder() { // @Override public <C> AMethodCall<C> of(Class<C> targetClass) { return new AMethodCall<C>(methodName, targetClass); } // }; // } // // private AMethodCall(String methodName, Class<C> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // public AMethodCall<C> with(AnArgument<?> anArgument) { // arguments.add(anArgument); // return this; // } // // public AMethodCall<C> and(AnArgument<?> anArgument) { // arguments.add(anArgument); // return this; // } // // @Override // public void describeTo(Description description) { // description.appendText(" a method call to the method ").appendValue(methodName).appendText(" on class ").appendValue(targetClass); // if (arguments.size() > 0) { // description.appendText(" with arguments ").appendValueList("[", ",", "]", arguments); // } // } // // @Override // protected boolean matchesSafely(MethodCall item, Description mismatchDescription) { // if (!item.targetClass().equals(targetClass)) { // mismatchDescription.appendText(" the target class was ").appendValue(targetClass); // return false; // } // if (!item.name().equals(methodName)) { // mismatchDescription.appendText(" the method called was ").appendText(methodName); // return false; // } // if (arguments.size() != item.arguments().size()) { // mismatchDescription.appendText(" the number of arguments was ").appendValue(item.arguments().size()); // return false; // } // Iterator<AnArgument<?>> matcherIterator = arguments.iterator(); // Iterator<MethodCallArgument<?>> argumentIterator = item.arguments().iterator(); // int argumentIndex = 0; // while (matcherIterator.hasNext()) { // AnArgument<?> matcher = matcherIterator.next(); // MethodCallArgument<?> argument = argumentIterator.next(); // argumentIndex += 1; // if (!matcher.matches(argument)) { // mismatchDescription.appendText(" argument [").appendValue(argumentIndex).appendText("]"); // matcher.describeMismatch(argument, mismatchDescription); // return false; // } // } // return true; // } // } // // Path: src/test/java/com/timgroup/stanislavski/matchers/AnArgument.java // public final class AnArgument<C> extends TypeSafeDiagnosingMatcher<MethodCallArgument<C>> { // private final C value; // // public static <C> AnArgument<C> of(C value) { // return new AnArgument<C>(value); // } // // private AnArgument(C value) { // this.value = value; // } // // @Override // public void describeTo(Description description) { // description.appendText(" an argument with the value ").appendValue(value); // } // // @Override // protected boolean matchesSafely(MethodCallArgument<C> item, Description mismatchDescription) { // if (item.value().equals(value)) { // return true; // } // mismatchDescription.appendText(" had the value ").appendValue(value); // return false; // } // // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.stanislavski.matchers.AMethodCall; import com.timgroup.stanislavski.matchers.AnArgument; import com.timgroup.stanislavski.reflection.MethodCall; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo;
package com.timgroup.stanislavski.recording; public class InterceptingMethodCallRecorderTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
// Path: src/test/java/com/timgroup/stanislavski/matchers/AMethodCall.java // public final class AMethodCall<C> extends TypeSafeDiagnosingMatcher<MethodCall> { // private final String methodName; // private final Class<C> targetClass; // private final Collection<AnArgument<?>> arguments = Lists.newLinkedList(); // // public static interface MethodNameBinder { // <C> AMethodCall<C> of(Class<C> interfaceClass); // } // // public static AMethodCall.MethodNameBinder to(final String methodName) { // return new MethodNameBinder() { // @Override public <C> AMethodCall<C> of(Class<C> targetClass) { return new AMethodCall<C>(methodName, targetClass); } // }; // } // // private AMethodCall(String methodName, Class<C> targetClass) { // this.methodName = methodName; // this.targetClass = targetClass; // } // // public AMethodCall<C> with(AnArgument<?> anArgument) { // arguments.add(anArgument); // return this; // } // // public AMethodCall<C> and(AnArgument<?> anArgument) { // arguments.add(anArgument); // return this; // } // // @Override // public void describeTo(Description description) { // description.appendText(" a method call to the method ").appendValue(methodName).appendText(" on class ").appendValue(targetClass); // if (arguments.size() > 0) { // description.appendText(" with arguments ").appendValueList("[", ",", "]", arguments); // } // } // // @Override // protected boolean matchesSafely(MethodCall item, Description mismatchDescription) { // if (!item.targetClass().equals(targetClass)) { // mismatchDescription.appendText(" the target class was ").appendValue(targetClass); // return false; // } // if (!item.name().equals(methodName)) { // mismatchDescription.appendText(" the method called was ").appendText(methodName); // return false; // } // if (arguments.size() != item.arguments().size()) { // mismatchDescription.appendText(" the number of arguments was ").appendValue(item.arguments().size()); // return false; // } // Iterator<AnArgument<?>> matcherIterator = arguments.iterator(); // Iterator<MethodCallArgument<?>> argumentIterator = item.arguments().iterator(); // int argumentIndex = 0; // while (matcherIterator.hasNext()) { // AnArgument<?> matcher = matcherIterator.next(); // MethodCallArgument<?> argument = argumentIterator.next(); // argumentIndex += 1; // if (!matcher.matches(argument)) { // mismatchDescription.appendText(" argument [").appendValue(argumentIndex).appendText("]"); // matcher.describeMismatch(argument, mismatchDescription); // return false; // } // } // return true; // } // } // // Path: src/test/java/com/timgroup/stanislavski/matchers/AnArgument.java // public final class AnArgument<C> extends TypeSafeDiagnosingMatcher<MethodCallArgument<C>> { // private final C value; // // public static <C> AnArgument<C> of(C value) { // return new AnArgument<C>(value); // } // // private AnArgument(C value) { // this.value = value; // } // // @Override // public void describeTo(Description description) { // description.appendText(" an argument with the value ").appendValue(value); // } // // @Override // protected boolean matchesSafely(MethodCallArgument<C> item, Description mismatchDescription) { // if (item.value().equals(value)) { // return true; // } // mismatchDescription.appendText(" had the value ").appendValue(value); // return false; // } // // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/test/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorderTest.java import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.stanislavski.matchers.AMethodCall; import com.timgroup.stanislavski.matchers.AnArgument; import com.timgroup.stanislavski.reflection.MethodCall; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; package com.timgroup.stanislavski.recording; public class InterceptingMethodCallRecorderTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
private final Predicate<MethodCall> finalCallMatcher = context.mock(Predicate.class);
tim-group/stanislavski
src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java
// Path: src/main/java/com/timgroup/stanislavski/recording/FinalCallHandler.java // public interface FinalCallHandler<T> { // T handle(MethodCall closingCall, Iterable<MethodCall> callHistory); // } // // Path: src/main/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorder.java // public class InterceptingMethodCallRecorder<T> implements MethodCallHandler { // // private final Predicate<MethodCall> finalCallMatcher; // private final FinalCallHandler<T> finalCallHandler; // private final ProxyFactory proxyFactory; // private final MethodCallRecorder recorder; // // public static <I, T, R> I proxying(Class<I> interfaceType, // Predicate<MethodCall> finalCallMatcher, // FinalCallHandler<T> finalCallHandler) { // return new InterceptingMethodCallRecorder<T>(finalCallMatcher, finalCallHandler).proxyFactory.getProxy(interfaceType); // } // // private InterceptingMethodCallRecorder(Predicate<MethodCall> predicate, // FinalCallHandler<T> methodCallDispatcher) { // this.finalCallMatcher = predicate; // this.finalCallHandler = methodCallDispatcher; // this.proxyFactory = ProxyFactory.forMethodCallHandler(this); // this.recorder = new MethodCallRecorder(); // } // // @Override public Object handle(MethodCall methodCall) { // if (finalCallMatcher.apply(methodCall)) { // return finalCallHandler.handle(methodCall, recorder.callHistory()); // } // recorder.record(methodCall); // return proxyFactory.getProxy(methodCall.returnType()); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // }
import org.hamcrest.Matcher; import org.hamcrest.SelfDescribing; import com.google.common.base.Predicate; import com.timgroup.stanislavski.recording.FinalCallHandler; import com.timgroup.stanislavski.recording.InterceptingMethodCallRecorder; import com.timgroup.stanislavski.reflection.MethodCall;
package com.timgroup.stanislavski.magic.matchers; public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { private final Class<T> targetClass; public static class MagicJavaBeanMatcherBuilder<T> { private Class<T> targetClass; private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { this.targetClass = targetClass; } public <I> I using(Class<I> interfaceClass) { MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass);
// Path: src/main/java/com/timgroup/stanislavski/recording/FinalCallHandler.java // public interface FinalCallHandler<T> { // T handle(MethodCall closingCall, Iterable<MethodCall> callHistory); // } // // Path: src/main/java/com/timgroup/stanislavski/recording/InterceptingMethodCallRecorder.java // public class InterceptingMethodCallRecorder<T> implements MethodCallHandler { // // private final Predicate<MethodCall> finalCallMatcher; // private final FinalCallHandler<T> finalCallHandler; // private final ProxyFactory proxyFactory; // private final MethodCallRecorder recorder; // // public static <I, T, R> I proxying(Class<I> interfaceType, // Predicate<MethodCall> finalCallMatcher, // FinalCallHandler<T> finalCallHandler) { // return new InterceptingMethodCallRecorder<T>(finalCallMatcher, finalCallHandler).proxyFactory.getProxy(interfaceType); // } // // private InterceptingMethodCallRecorder(Predicate<MethodCall> predicate, // FinalCallHandler<T> methodCallDispatcher) { // this.finalCallMatcher = predicate; // this.finalCallHandler = methodCallDispatcher; // this.proxyFactory = ProxyFactory.forMethodCallHandler(this); // this.recorder = new MethodCallRecorder(); // } // // @Override public Object handle(MethodCall methodCall) { // if (finalCallMatcher.apply(methodCall)) { // return finalCallHandler.handle(methodCall, recorder.callHistory()); // } // recorder.record(methodCall); // return proxyFactory.getProxy(methodCall.returnType()); // } // } // // Path: src/main/java/com/timgroup/stanislavski/reflection/MethodCall.java // public class MethodCall { // private final Method method; // private final Object[] rawArgs; // private final List<MethodCallArgument<?>> arguments; // // public static MethodCall create(Method method, Object...args) { // return new MethodCall(method, args); // } // // private MethodCall(Method method, Object[] rawArgs) { // this.method = method; // this.rawArgs = rawArgs; // this.arguments = MethodCallArgument.wrapArguments(method, rawArgs); // } // // public Class<?> targetClass() { // return method.getDeclaringClass(); // } // // public Class<?> returnType() { // return method.getReturnType(); // } // // public String name() { // return method.getName(); // } // // public List<MethodCallArgument<?>> arguments() { // return arguments; // } // // public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { // return method.isAnnotationPresent(annotationClass); // } // // public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { // return method.getAnnotation(annotationClass); // } // // public MethodCallArgument<?> firstArgument() { // return arguments.get(0); // } // // public Object applyTo(Object target) throws Throwable { // try { // return this.method.invoke(target, rawArgs); // } catch (InvocationTargetException e) { // throw e.getCause(); // } // } // // @Override public String toString() { // return String.format("%s: %s", method, arguments); // } // // public List<Object> argumentValues() { // return Lists.transform(arguments, MethodCallArgument.TO_VALUE); // } // } // Path: src/main/java/com/timgroup/stanislavski/magic/matchers/MagicJavaBeanMatcher.java import org.hamcrest.Matcher; import org.hamcrest.SelfDescribing; import com.google.common.base.Predicate; import com.timgroup.stanislavski.recording.FinalCallHandler; import com.timgroup.stanislavski.recording.InterceptingMethodCallRecorder; import com.timgroup.stanislavski.reflection.MethodCall; package com.timgroup.stanislavski.magic.matchers; public final class MagicJavaBeanMatcher<T, I> implements Predicate<MethodCall>, FinalCallHandler<Object> { private final Class<T> targetClass; public static class MagicJavaBeanMatcherBuilder<T> { private Class<T> targetClass; private MagicJavaBeanMatcherBuilder(Class<T> targetClass) { this.targetClass = targetClass; } public <I> I using(Class<I> interfaceClass) { MagicJavaBeanMatcher<T, I> matcher = new MagicJavaBeanMatcher<T, I>(targetClass);
return InterceptingMethodCallRecorder.proxying(interfaceClass, matcher, matcher);
teozfrank/DuelMe
WorldEditLegacy/src/main/java/com/github/teozfrank/duelme/worldedit/legacy/WorldEditLegacy.java
// Path: API/src/main/java/com/github/teozfrank/duelme/api/WorldEditSelectionHelper.java // public interface WorldEditSelectionHelper { // WorldEditSelection getWorldEditSelection(Player player); // } // // Path: API/src/main/java/util/WorldEditSelection.java // public class WorldEditSelection { // // private Location pos1; // private Location pos2; // // private boolean success; // // public WorldEditSelection() { // // } // // public WorldEditSelection(Location pos1, Location pos2, boolean success) { // this.pos1 = pos1; // this.pos2 = pos2; // this.success = success; // } // // public Location getPos1() { // return pos1; // } // // public void setPos1(Location pos1) { // this.pos1 = pos1; // } // // public Location getPos2() { // return pos2; // } // // public void setPos2(Location pos2) { // this.pos2 = pos2; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // @Override // public String toString() { // String returnString = ""; // if(pos1 == null || pos2 == null) { // returnString = "Selection is null or incomplete"; // } else { // returnString = "WorldEditSelection{" + // // "pos1W=" + pos1.getWorld().getName() + // "pos1X=" + pos1.getBlockX() + // "pos1Y=" + pos1.getBlockY() + // "pos1Z=" + pos1.getBlockZ() +"\n" + // "pos2W=" + pos2.getWorld().getName() + // "pos2X=" + pos2.getBlockX() + // "pos2Y=" + pos2.getBlockY() + // "pos2Z=" + pos2.getBlockZ() +"\n" + // "success=" + success + // '}'; // } // return returnString; // } // }
import com.github.teozfrank.duelme.api.WorldEditSelectionHelper; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.selections.Selection; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import util.WorldEditSelection;
package com.github.teozfrank.duelme.worldedit.legacy; public class WorldEditLegacy implements WorldEditSelectionHelper { @Override
// Path: API/src/main/java/com/github/teozfrank/duelme/api/WorldEditSelectionHelper.java // public interface WorldEditSelectionHelper { // WorldEditSelection getWorldEditSelection(Player player); // } // // Path: API/src/main/java/util/WorldEditSelection.java // public class WorldEditSelection { // // private Location pos1; // private Location pos2; // // private boolean success; // // public WorldEditSelection() { // // } // // public WorldEditSelection(Location pos1, Location pos2, boolean success) { // this.pos1 = pos1; // this.pos2 = pos2; // this.success = success; // } // // public Location getPos1() { // return pos1; // } // // public void setPos1(Location pos1) { // this.pos1 = pos1; // } // // public Location getPos2() { // return pos2; // } // // public void setPos2(Location pos2) { // this.pos2 = pos2; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // @Override // public String toString() { // String returnString = ""; // if(pos1 == null || pos2 == null) { // returnString = "Selection is null or incomplete"; // } else { // returnString = "WorldEditSelection{" + // // "pos1W=" + pos1.getWorld().getName() + // "pos1X=" + pos1.getBlockX() + // "pos1Y=" + pos1.getBlockY() + // "pos1Z=" + pos1.getBlockZ() +"\n" + // "pos2W=" + pos2.getWorld().getName() + // "pos2X=" + pos2.getBlockX() + // "pos2Y=" + pos2.getBlockY() + // "pos2Z=" + pos2.getBlockZ() +"\n" + // "success=" + success + // '}'; // } // return returnString; // } // } // Path: WorldEditLegacy/src/main/java/com/github/teozfrank/duelme/worldedit/legacy/WorldEditLegacy.java import com.github.teozfrank.duelme.api.WorldEditSelectionHelper; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.selections.Selection; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import util.WorldEditSelection; package com.github.teozfrank.duelme.worldedit.legacy; public class WorldEditLegacy implements WorldEditSelectionHelper { @Override
public WorldEditSelection getWorldEditSelection(Player player) {
teozfrank/DuelMe
WorldEditLatest/src/main/java/com/github/teozfrank/duelme/worldedit/latest/WorldEditLatest.java
// Path: API/src/main/java/com/github/teozfrank/duelme/api/WorldEditSelectionHelper.java // public interface WorldEditSelectionHelper { // WorldEditSelection getWorldEditSelection(Player player); // } // // Path: API/src/main/java/util/WorldEditSelection.java // public class WorldEditSelection { // // private Location pos1; // private Location pos2; // // private boolean success; // // public WorldEditSelection() { // // } // // public WorldEditSelection(Location pos1, Location pos2, boolean success) { // this.pos1 = pos1; // this.pos2 = pos2; // this.success = success; // } // // public Location getPos1() { // return pos1; // } // // public void setPos1(Location pos1) { // this.pos1 = pos1; // } // // public Location getPos2() { // return pos2; // } // // public void setPos2(Location pos2) { // this.pos2 = pos2; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // @Override // public String toString() { // String returnString = ""; // if(pos1 == null || pos2 == null) { // returnString = "Selection is null or incomplete"; // } else { // returnString = "WorldEditSelection{" + // // "pos1W=" + pos1.getWorld().getName() + // "pos1X=" + pos1.getBlockX() + // "pos1Y=" + pos1.getBlockY() + // "pos1Z=" + pos1.getBlockZ() +"\n" + // "pos2W=" + pos2.getWorld().getName() + // "pos2X=" + pos2.getBlockX() + // "pos2Y=" + pos2.getBlockY() + // "pos2Z=" + pos2.getBlockZ() +"\n" + // "success=" + success + // '}'; // } // return returnString; // } // }
import com.github.teozfrank.duelme.api.WorldEditSelectionHelper; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.SessionOwner; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import util.WorldEditSelection;
package com.github.teozfrank.duelme.worldedit.latest; public class WorldEditLatest implements WorldEditSelectionHelper { @Override
// Path: API/src/main/java/com/github/teozfrank/duelme/api/WorldEditSelectionHelper.java // public interface WorldEditSelectionHelper { // WorldEditSelection getWorldEditSelection(Player player); // } // // Path: API/src/main/java/util/WorldEditSelection.java // public class WorldEditSelection { // // private Location pos1; // private Location pos2; // // private boolean success; // // public WorldEditSelection() { // // } // // public WorldEditSelection(Location pos1, Location pos2, boolean success) { // this.pos1 = pos1; // this.pos2 = pos2; // this.success = success; // } // // public Location getPos1() { // return pos1; // } // // public void setPos1(Location pos1) { // this.pos1 = pos1; // } // // public Location getPos2() { // return pos2; // } // // public void setPos2(Location pos2) { // this.pos2 = pos2; // } // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // @Override // public String toString() { // String returnString = ""; // if(pos1 == null || pos2 == null) { // returnString = "Selection is null or incomplete"; // } else { // returnString = "WorldEditSelection{" + // // "pos1W=" + pos1.getWorld().getName() + // "pos1X=" + pos1.getBlockX() + // "pos1Y=" + pos1.getBlockY() + // "pos1Z=" + pos1.getBlockZ() +"\n" + // "pos2W=" + pos2.getWorld().getName() + // "pos2X=" + pos2.getBlockX() + // "pos2Y=" + pos2.getBlockY() + // "pos2Z=" + pos2.getBlockZ() +"\n" + // "success=" + success + // '}'; // } // return returnString; // } // } // Path: WorldEditLatest/src/main/java/com/github/teozfrank/duelme/worldedit/latest/WorldEditLatest.java import com.github.teozfrank.duelme.api.WorldEditSelectionHelper; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.SessionOwner; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import util.WorldEditSelection; package com.github.teozfrank.duelme.worldedit.latest; public class WorldEditLatest implements WorldEditSelectionHelper { @Override
public WorldEditSelection getWorldEditSelection(Player player) {
jwboardman/whirlpool
whirlpoolserver/src/main/java/com/khs/microservice/whirlpool/whirlpoolserver/WhirlpoolKafkaProducer.java
// Path: common/src/main/java/com/khs/microservice/whirlpool/common/Message.java // public class Message { // private String type; // private String id; // // public String getType() { return type; } // // public void setType(String type) { this.type = type; } // // public String getId() { return id; } // // public void setId(String id) { this.id = id; } // // @Override // public boolean equals(Object o) { // if (this == o) { return true; } // if (o == null || getClass() != o.getClass()) { return false; } // // Message that = (Message) o; // // if (type != null ? !type.equals(that.type) : that.type != null) { return false; } // if (id != null ? !id.equals(that.id) : that.id != null) { return false; } // // return true; // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + (this.id != null ? this.id.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Message{" + // "type='" + type + "'" + // ", id='" + id + "'" + // "}"; // } // }
import com.google.common.io.Resources; import com.google.gson.Gson; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.khs.microservice.whirlpool.common.Message;
package com.khs.microservice.whirlpool.whirlpoolserver; /** * This class waits for command requests from the client request queue, * then sends them to Kafka * * @author jwb */ public class WhirlpoolKafkaProducer implements Callable<String> { private static final Logger logger = LoggerFactory.getLogger(WhirlpoolKafkaProducer.class); private static final AtomicBoolean keepRunning = new AtomicBoolean(true); private ConcurrentLinkedQueue<String> requestQueue; private Gson gson = new Gson(); WhirlpoolKafkaProducer(ConcurrentLinkedQueue<String> requestQueue) { this.requestQueue = requestQueue; } @Override public String call() throws Exception { // set up the producer KafkaProducer<String, String> producer; try (InputStream props = Resources.getResource("producer.props").openStream()) { Properties properties = new Properties(); properties.load(props); producer = new KafkaProducer<>(properties); } try { String request; while (keepRunning.get()) { while ((request = requestQueue.poll()) != null) { // simple class containing only the type
// Path: common/src/main/java/com/khs/microservice/whirlpool/common/Message.java // public class Message { // private String type; // private String id; // // public String getType() { return type; } // // public void setType(String type) { this.type = type; } // // public String getId() { return id; } // // public void setId(String id) { this.id = id; } // // @Override // public boolean equals(Object o) { // if (this == o) { return true; } // if (o == null || getClass() != o.getClass()) { return false; } // // Message that = (Message) o; // // if (type != null ? !type.equals(that.type) : that.type != null) { return false; } // if (id != null ? !id.equals(that.id) : that.id != null) { return false; } // // return true; // } // // @Override // public int hashCode() { // int result = type != null ? type.hashCode() : 0; // result = 31 * result + (this.id != null ? this.id.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Message{" + // "type='" + type + "'" + // ", id='" + id + "'" + // "}"; // } // } // Path: whirlpoolserver/src/main/java/com/khs/microservice/whirlpool/whirlpoolserver/WhirlpoolKafkaProducer.java import com.google.common.io.Resources; import com.google.gson.Gson; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.khs.microservice.whirlpool.common.Message; package com.khs.microservice.whirlpool.whirlpoolserver; /** * This class waits for command requests from the client request queue, * then sends them to Kafka * * @author jwb */ public class WhirlpoolKafkaProducer implements Callable<String> { private static final Logger logger = LoggerFactory.getLogger(WhirlpoolKafkaProducer.class); private static final AtomicBoolean keepRunning = new AtomicBoolean(true); private ConcurrentLinkedQueue<String> requestQueue; private Gson gson = new Gson(); WhirlpoolKafkaProducer(ConcurrentLinkedQueue<String> requestQueue) { this.requestQueue = requestQueue; } @Override public String call() throws Exception { // set up the producer KafkaProducer<String, String> producer; try (InputStream props = Resources.getResource("producer.props").openStream()) { Properties properties = new Properties(); properties.load(props); producer = new KafkaProducer<>(properties); } try { String request; while (keepRunning.get()) { while ((request = requestQueue.poll()) != null) { // simple class containing only the type
Message message = gson.fromJson(request, Message.class);
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/provider/jx/json/JsonWebSocketHandler.java
// Path: src/main/java/edu/stanford/junction/provider/jx/JXServer.java // public static class Log { // public static void d(String tag, String msg) { // System.out.println(tag + ": " + msg); // } // // public static void e(String tag, String msg) { // System.err.println(tag + ": " + msg); // } // // public static void e(String tag, String msg, Exception e) { // System.err.println(tag + ": " + msg); // e.printStackTrace(System.err); // } // }
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.json.JSONException; import org.json.JSONObject; import edu.stanford.junction.provider.jx.JXServer.Log;
package edu.stanford.junction.provider.jx.json; /** * Helps read and write json messages over a WebSocket. * */ public class JsonWebSocketHandler extends JsonHandler { private static final int BUFFER_SIZE = 1024; private final OutputStream out; private final InputStream in; public JsonWebSocketHandler(InputStream in, OutputStream out) { this.in = in; this.out = new BufferedOutputStream(out); } public void sendJson(JSONObject message) throws IOException { byte[] bytes = message.toString().getBytes(); out.write(0x00); out.write(bytes, 0, bytes.length); out.write(0x000000FF); out.flush(); } private byte[] buffer = new byte[BUFFER_SIZE]; private int byteCount; /** * Reads a JSON object from the handler's inputStream. * This method is not thread safe. */ public JSONObject jsonFromStream() throws IOException { while (true) { try { byteCount = in.read(buffer); if (byteCount == -1) { break; } if (buffer[0] != 0x00) {
// Path: src/main/java/edu/stanford/junction/provider/jx/JXServer.java // public static class Log { // public static void d(String tag, String msg) { // System.out.println(tag + ": " + msg); // } // // public static void e(String tag, String msg) { // System.err.println(tag + ": " + msg); // } // // public static void e(String tag, String msg, Exception e) { // System.err.println(tag + ": " + msg); // e.printStackTrace(System.err); // } // } // Path: src/main/java/edu/stanford/junction/provider/jx/json/JsonWebSocketHandler.java import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.json.JSONException; import org.json.JSONObject; import edu.stanford.junction.provider.jx.JXServer.Log; package edu.stanford.junction.provider.jx.json; /** * Helps read and write json messages over a WebSocket. * */ public class JsonWebSocketHandler extends JsonHandler { private static final int BUFFER_SIZE = 1024; private final OutputStream out; private final InputStream in; public JsonWebSocketHandler(InputStream in, OutputStream out) { this.in = in; this.out = new BufferedOutputStream(out); } public void sendJson(JSONObject message) throws IOException { byte[] bytes = message.toString().getBytes(); out.write(0x00); out.write(bytes, 0, bytes.length); out.write(0x000000FF); out.flush(); } private byte[] buffer = new byte[BUFFER_SIZE]; private int byteCount; /** * Reads a JSON object from the handler's inputStream. * This method is not thread safe. */ public JSONObject jsonFromStream() throws IOException { while (true) { try { byteCount = in.read(buffer); if (byteCount == -1) { break; } if (buffer[0] != 0x00) {
Log.e(TAG, "Bad frame header found in WebSocket connection");
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/props2/sample/SetProp.java
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // }
import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp; import org.json.JSONObject; import java.util.*;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class SetProp extends CollectionProp { public SetProp(String propName, String propReplicaName, Collection<JSONObject> items){ super(propName, propReplicaName, new SetState(items)); }
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // } // Path: src/main/java/edu/stanford/junction/props2/sample/SetProp.java import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp; import org.json.JSONObject; import java.util.*; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class SetProp extends CollectionProp { public SetProp(String propName, String propReplicaName, Collection<JSONObject> items){ super(propName, propReplicaName, new SetState(items)); }
public SetProp(String propName, String propReplicaName, IPropState s){
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/props2/sample/SetProp.java
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // }
import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp; import org.json.JSONObject; import java.util.*;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class SetProp extends CollectionProp { public SetProp(String propName, String propReplicaName, Collection<JSONObject> items){ super(propName, propReplicaName, new SetState(items)); } public SetProp(String propName, String propReplicaName, IPropState s){ super(propName, propReplicaName, s); } public SetProp(String propName, String propReplicaName){ this(propName, propReplicaName, new ArrayList<JSONObject>()); }
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // } // Path: src/main/java/edu/stanford/junction/props2/sample/SetProp.java import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp; import org.json.JSONObject; import java.util.*; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class SetProp extends CollectionProp { public SetProp(String propName, String propReplicaName, Collection<JSONObject> items){ super(propName, propReplicaName, new SetState(items)); } public SetProp(String propName, String propReplicaName, IPropState s){ super(propName, propReplicaName, s); } public SetProp(String propName, String propReplicaName){ this(propName, propReplicaName, new ArrayList<JSONObject>()); }
public IProp newFresh(){
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/provider/jvm/MultiJunction.java
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionActor.java // public abstract class JunctionActor { // protected Junction mJunction; // private String actorID; // private String[] mRoles; // // public String[] getRoles() { // return mRoles; // } // // public JunctionActor() { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{}; // } // // public JunctionActor(String role) { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{role}; // } // // public JunctionActor(String[] roles) { // actorID = UUID.randomUUID().toString(); // mRoles=roles; // } // // public void onActivityJoin() { // // } // // public void setJunction(Junction j) { // mJunction=j; // } // // public Junction getJunction() { // return mJunction; // } // // public String getActorID() { // return actorID; // } // // public void onActivityStart() { // // } // // public final void leave() { // Junction jx = getJunction(); // if (jx != null) { // jx.disconnect(); // setJunction(null); // } // } // // public void onActivityCreate() { // // } // // /** // * Send a message to an individual actor, identified by actorID // */ // public void sendMessageToActor(String actorID, JSONObject message) { // mJunction.sendMessageToActor(actorID, message); // } // // /** // * Send a message for anyone in the Junction session. // */ // public void sendMessageToSession(JSONObject message) { // mJunction.sendMessageToSession(message); // } // // /** // * Send a message to an actor claiming a certain role. // */ // public void sendMessageToRole(String role, JSONObject message) { // mJunction.sendMessageToRole(role, message); // } // // /** // * Asynchronously handle an inbound message. // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * Returns a list of JunctionExtras that should be loaded // * when the actor joins an activity // * @return // */ // public List<JunctionExtra>getInitialExtras() { // return new ArrayList<JunctionExtra>(); // } // // public void registerExtra(JunctionExtra extra) { // mJunction.registerExtra(extra); // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // }
import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionActor; import edu.stanford.junction.api.messaging.MessageHeader;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.provider.jvm; public class MultiJunction { private static Map<URI,MultiJunction>multiJunctions = Collections.synchronizedMap( new HashMap<URI,MultiJunction>());
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionActor.java // public abstract class JunctionActor { // protected Junction mJunction; // private String actorID; // private String[] mRoles; // // public String[] getRoles() { // return mRoles; // } // // public JunctionActor() { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{}; // } // // public JunctionActor(String role) { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{role}; // } // // public JunctionActor(String[] roles) { // actorID = UUID.randomUUID().toString(); // mRoles=roles; // } // // public void onActivityJoin() { // // } // // public void setJunction(Junction j) { // mJunction=j; // } // // public Junction getJunction() { // return mJunction; // } // // public String getActorID() { // return actorID; // } // // public void onActivityStart() { // // } // // public final void leave() { // Junction jx = getJunction(); // if (jx != null) { // jx.disconnect(); // setJunction(null); // } // } // // public void onActivityCreate() { // // } // // /** // * Send a message to an individual actor, identified by actorID // */ // public void sendMessageToActor(String actorID, JSONObject message) { // mJunction.sendMessageToActor(actorID, message); // } // // /** // * Send a message for anyone in the Junction session. // */ // public void sendMessageToSession(JSONObject message) { // mJunction.sendMessageToSession(message); // } // // /** // * Send a message to an actor claiming a certain role. // */ // public void sendMessageToRole(String role, JSONObject message) { // mJunction.sendMessageToRole(role, message); // } // // /** // * Asynchronously handle an inbound message. // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * Returns a list of JunctionExtras that should be loaded // * when the actor joins an activity // * @return // */ // public List<JunctionExtra>getInitialExtras() { // return new ArrayList<JunctionExtra>(); // } // // public void registerExtra(JunctionExtra extra) { // mJunction.registerExtra(extra); // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // } // Path: src/main/java/edu/stanford/junction/provider/jvm/MultiJunction.java import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionActor; import edu.stanford.junction.api.messaging.MessageHeader; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.provider.jvm; public class MultiJunction { private static Map<URI,MultiJunction>multiJunctions = Collections.synchronizedMap( new HashMap<URI,MultiJunction>());
Map<String,JunctionActor> actorMap;
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/provider/jvm/MultiJunction.java
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionActor.java // public abstract class JunctionActor { // protected Junction mJunction; // private String actorID; // private String[] mRoles; // // public String[] getRoles() { // return mRoles; // } // // public JunctionActor() { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{}; // } // // public JunctionActor(String role) { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{role}; // } // // public JunctionActor(String[] roles) { // actorID = UUID.randomUUID().toString(); // mRoles=roles; // } // // public void onActivityJoin() { // // } // // public void setJunction(Junction j) { // mJunction=j; // } // // public Junction getJunction() { // return mJunction; // } // // public String getActorID() { // return actorID; // } // // public void onActivityStart() { // // } // // public final void leave() { // Junction jx = getJunction(); // if (jx != null) { // jx.disconnect(); // setJunction(null); // } // } // // public void onActivityCreate() { // // } // // /** // * Send a message to an individual actor, identified by actorID // */ // public void sendMessageToActor(String actorID, JSONObject message) { // mJunction.sendMessageToActor(actorID, message); // } // // /** // * Send a message for anyone in the Junction session. // */ // public void sendMessageToSession(JSONObject message) { // mJunction.sendMessageToSession(message); // } // // /** // * Send a message to an actor claiming a certain role. // */ // public void sendMessageToRole(String role, JSONObject message) { // mJunction.sendMessageToRole(role, message); // } // // /** // * Asynchronously handle an inbound message. // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * Returns a list of JunctionExtras that should be loaded // * when the actor joins an activity // * @return // */ // public List<JunctionExtra>getInitialExtras() { // return new ArrayList<JunctionExtra>(); // } // // public void registerExtra(JunctionExtra extra) { // mJunction.registerExtra(extra); // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // }
import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionActor; import edu.stanford.junction.api.messaging.MessageHeader;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.provider.jvm; public class MultiJunction { private static Map<URI,MultiJunction>multiJunctions = Collections.synchronizedMap( new HashMap<URI,MultiJunction>()); Map<String,JunctionActor> actorMap; URI uri; public static MultiJunction get(URI uri, JunctionActor actor) { MultiJunction j; if (!multiJunctions.containsKey(uri)) { j = new MultiJunction(uri); multiJunctions.put(uri,j); } else { j = multiJunctions.get(uri); } j.registerActor(actor); return j; } private MultiJunction(URI uri) { actorMap = new HashMap<String, JunctionActor>(); this.uri = uri; } private void registerActor(JunctionActor actor) { actorMap.put(actor.getActorID(),actor); } protected void sendMessageToActor(JunctionActor from, String actorID, JSONObject message) { if (actorMap.containsKey(actorID)) { actorMap.get(actorID).getJunction().triggerMessageReceived(
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionActor.java // public abstract class JunctionActor { // protected Junction mJunction; // private String actorID; // private String[] mRoles; // // public String[] getRoles() { // return mRoles; // } // // public JunctionActor() { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{}; // } // // public JunctionActor(String role) { // actorID = UUID.randomUUID().toString(); // mRoles = new String[]{role}; // } // // public JunctionActor(String[] roles) { // actorID = UUID.randomUUID().toString(); // mRoles=roles; // } // // public void onActivityJoin() { // // } // // public void setJunction(Junction j) { // mJunction=j; // } // // public Junction getJunction() { // return mJunction; // } // // public String getActorID() { // return actorID; // } // // public void onActivityStart() { // // } // // public final void leave() { // Junction jx = getJunction(); // if (jx != null) { // jx.disconnect(); // setJunction(null); // } // } // // public void onActivityCreate() { // // } // // /** // * Send a message to an individual actor, identified by actorID // */ // public void sendMessageToActor(String actorID, JSONObject message) { // mJunction.sendMessageToActor(actorID, message); // } // // /** // * Send a message for anyone in the Junction session. // */ // public void sendMessageToSession(JSONObject message) { // mJunction.sendMessageToSession(message); // } // // /** // * Send a message to an actor claiming a certain role. // */ // public void sendMessageToRole(String role, JSONObject message) { // mJunction.sendMessageToRole(role, message); // } // // /** // * Asynchronously handle an inbound message. // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * Returns a list of JunctionExtras that should be loaded // * when the actor joins an activity // * @return // */ // public List<JunctionExtra>getInitialExtras() { // return new ArrayList<JunctionExtra>(); // } // // public void registerExtra(JunctionExtra extra) { // mJunction.registerExtra(extra); // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // } // Path: src/main/java/edu/stanford/junction/provider/jvm/MultiJunction.java import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionActor; import edu.stanford.junction.api.messaging.MessageHeader; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.provider.jvm; public class MultiJunction { private static Map<URI,MultiJunction>multiJunctions = Collections.synchronizedMap( new HashMap<URI,MultiJunction>()); Map<String,JunctionActor> actorMap; URI uri; public static MultiJunction get(URI uri, JunctionActor actor) { MultiJunction j; if (!multiJunctions.containsKey(uri)) { j = new MultiJunction(uri); multiJunctions.put(uri,j); } else { j = multiJunctions.get(uri); } j.registerActor(actor); return j; } private MultiJunction(URI uri) { actorMap = new HashMap<String, JunctionActor>(); this.uri = uri; } private void registerActor(JunctionActor actor) { actorMap.put(actor.getActorID(),actor); } protected void sendMessageToActor(JunctionActor from, String actorID, JSONObject message) { if (actorMap.containsKey(actorID)) { actorMap.get(actorID).getJunction().triggerMessageReceived(
new MessageHeader(from.getJunction(),message,from.getActorID()),
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/props2/sample/ListProp.java
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // }
import org.json.JSONObject; import java.util.*; import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class ListProp extends CollectionProp { public ListProp(String propName, String propReplicaName, IPropState s, long seqNum){ super(propName, propReplicaName, s, seqNum); } public ListProp(String propName, String propReplicaName, IPropState s){ this(propName, propReplicaName, s, 0); } public ListProp(String propName, String propReplicaName){ this(propName, propReplicaName, new ListState()); }
// Path: src/main/java/edu/stanford/junction/props2/IPropState.java // public interface IPropState{ // IPropState applyOperation(JSONObject operation); // JSONObject toJSON(); // IPropState copy(); // } // // Path: src/main/java/edu/stanford/junction/props2/IProp.java // public interface IProp{ // // /** // * The internal counter that tracks how many operations // * have been executed on this prop's state. For a given state, // * this number should be the same at all peers. // */ // public long getSequenceNum(); // // /** // * The name of the prop at large. All peers must share this name. // */ // public String getPropName(); // // public String getPropReplicaName(); // // public void addChangeListener(IPropChangeListener listener); // // public void removeChangeListener(IPropChangeListener listener); // // public void removeChangeListenersOfType(String type); // // public void removeAllChangeListeners(); // // public void addOperation(JSONObject operation); // // public IProp newFresh(); // // } // Path: src/main/java/edu/stanford/junction/props2/sample/ListProp.java import org.json.JSONObject; import java.util.*; import edu.stanford.junction.props2.IPropState; import edu.stanford.junction.props2.IProp; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.props2.sample; public class ListProp extends CollectionProp { public ListProp(String propName, String propReplicaName, IPropState s, long seqNum){ super(propName, propReplicaName, s, seqNum); } public ListProp(String propName, String propReplicaName, IPropState s){ this(propName, propReplicaName, s, 0); } public ListProp(String propName, String propReplicaName){ this(propName, propReplicaName, new ListState()); }
public IProp newFresh(){
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/simulator/ForwardingService.java
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionService.java // public abstract class JunctionService extends JunctionActor { // public static String SERVICE_CHANNEL="jxservice"; // // private static Map<String,Junction>mJunctionMap; // { // mJunctionMap = new HashMap<String,Junction>(); // } // // String mRole; // // public abstract String getServiceName(); // // public JunctionService() { // super((String)null); // } // // @Override // public String[] getRoles() { // return new String[] {mRole}; // } // // @Override // public void onActivityStart() {} // // public final void register(String switchboard) { // // if (mJunctionMap.containsKey(switchboard)) return; // // ActivityScript desc = new ActivityScript(); // desc.setHost(switchboard); // desc.setSessionID(SERVICE_CHANNEL); // //desc.setActorID(getServiceName()); // desc.setActivityID("junction.service"); // // // TODO: register(String sb) doesn't make sense any more. // // Get rid of 'services' in general; just stick an actor to an activity. // XMPPSwitchboardConfig config = new XMPPSwitchboardConfig(switchboard); // JunctionMaker maker = (JunctionMaker) JunctionMaker.getInstance(config); // // try{ // Junction jx = maker.newJunction(desc, this); // mJunctionMap.put(switchboard, jx); // } // catch(JunctionException e){ // System.err.println("Failed to register JunctionService"); // e.printStackTrace(System.err); // } // } // // public void setRole(String role) { // mRole=role; // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHandler.java // public abstract class MessageHandler { // /** // * Stream-selecting filters; // * These filters allow Junction to route messages // * using the network's capabilities. // * // * If we are sending to a fixed actor, try and establish a direct connection. // * If we are sending to a fixed role or multiple actors, we can // * potentially multicast. // * // * These methods should return static results (list of actors does not change // * over the lifetime of the handler) // */ // public List<String> supportedRoles() { return null; } // default is to not filter on roles. // public List<String> supportedActors() { return null; } // default is to not filter on actors. // public List<String> supportedChannels() { return null; } // default is to not filter on channel. // // /** // * Message-level filter // * // * These filters may be convenient for the end-user. // * May be useful to support RPC, for example // * // */ // public boolean supportsMessage(JSONObject message) { return true; } // // TODO: have a dynamic filter and a static one. // // the static one defines a message template, and this template can be // // shared (like an XML XSD document) // // /** // * Message handling // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * How to add response capabilities? // * This should be bridged with Junction.sendMessageToXXX // * We might need a MessageTarget or something. // */ // // getMessageRecipients; // // getMessageSender; // // replyToSender; // // replyAll // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // }
import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionService; import edu.stanford.junction.api.messaging.MessageHandler; import edu.stanford.junction.api.messaging.MessageHeader;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.simulator; /** * This class allows a remote client to subscribe to a channel without having * to open a new connection for it. It may be useful for a singleton service * expecting to connect to many activities. * @author bdodson * */ public class ForwardingService extends JunctionService { private String mChannel; // TODO: this needs to be on another server private ForwardingService() {} public static JunctionService newInstance() { return new ForwardingService(); } @Override public String getServiceName() { return "JunctionMaker"; } @Override public void onActivityStart() { } @Override public void onActivityJoin() { } @Override
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionService.java // public abstract class JunctionService extends JunctionActor { // public static String SERVICE_CHANNEL="jxservice"; // // private static Map<String,Junction>mJunctionMap; // { // mJunctionMap = new HashMap<String,Junction>(); // } // // String mRole; // // public abstract String getServiceName(); // // public JunctionService() { // super((String)null); // } // // @Override // public String[] getRoles() { // return new String[] {mRole}; // } // // @Override // public void onActivityStart() {} // // public final void register(String switchboard) { // // if (mJunctionMap.containsKey(switchboard)) return; // // ActivityScript desc = new ActivityScript(); // desc.setHost(switchboard); // desc.setSessionID(SERVICE_CHANNEL); // //desc.setActorID(getServiceName()); // desc.setActivityID("junction.service"); // // // TODO: register(String sb) doesn't make sense any more. // // Get rid of 'services' in general; just stick an actor to an activity. // XMPPSwitchboardConfig config = new XMPPSwitchboardConfig(switchboard); // JunctionMaker maker = (JunctionMaker) JunctionMaker.getInstance(config); // // try{ // Junction jx = maker.newJunction(desc, this); // mJunctionMap.put(switchboard, jx); // } // catch(JunctionException e){ // System.err.println("Failed to register JunctionService"); // e.printStackTrace(System.err); // } // } // // public void setRole(String role) { // mRole=role; // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHandler.java // public abstract class MessageHandler { // /** // * Stream-selecting filters; // * These filters allow Junction to route messages // * using the network's capabilities. // * // * If we are sending to a fixed actor, try and establish a direct connection. // * If we are sending to a fixed role or multiple actors, we can // * potentially multicast. // * // * These methods should return static results (list of actors does not change // * over the lifetime of the handler) // */ // public List<String> supportedRoles() { return null; } // default is to not filter on roles. // public List<String> supportedActors() { return null; } // default is to not filter on actors. // public List<String> supportedChannels() { return null; } // default is to not filter on channel. // // /** // * Message-level filter // * // * These filters may be convenient for the end-user. // * May be useful to support RPC, for example // * // */ // public boolean supportsMessage(JSONObject message) { return true; } // // TODO: have a dynamic filter and a static one. // // the static one defines a message template, and this template can be // // shared (like an XML XSD document) // // /** // * Message handling // */ // public abstract void onMessageReceived(MessageHeader header, JSONObject message); // // /** // * How to add response capabilities? // * This should be bridged with Junction.sendMessageToXXX // * We might need a MessageTarget or something. // */ // // getMessageRecipients; // // getMessageSender; // // replyToSender; // // replyAll // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // } // Path: src/main/java/edu/stanford/junction/simulator/ForwardingService.java import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionService; import edu.stanford.junction.api.messaging.MessageHandler; import edu.stanford.junction.api.messaging.MessageHeader; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.simulator; /** * This class allows a remote client to subscribe to a channel without having * to open a new connection for it. It may be useful for a singleton service * expecting to connect to many activities. * @author bdodson * */ public class ForwardingService extends JunctionService { private String mChannel; // TODO: this needs to be on another server private ForwardingService() {} public static JunctionService newInstance() { return new ForwardingService(); } @Override public String getServiceName() { return "JunctionMaker"; } @Override public void onActivityStart() { } @Override public void onActivityJoin() { } @Override
public void onMessageReceived(MessageHeader header, JSONObject message) {
OpenJunction/JavaJunction
src/main/java/edu/stanford/junction/extra/JXSystem.java
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionExtra.java // public abstract class JunctionExtra { // JunctionActor mParent=null; // // /** // * Provides access to the associated JunctionActor. // * @return // */ // public final JunctionActor getActor() { // return mParent; // } // // /** // * This method should only be called internally. // * @param actor // */ // public void setActor(JunctionActor actor) { // mParent=actor; // } // // /** // * Update the parameters that will be sent in an invitation // */ // public void updateInvitationParameters(Map<String,String>params) { // // } // // /** // * Returns true if the normal event handling should proceed; // * Return false to stop cascading. // */ // public boolean beforeOnMessageReceived(MessageHeader h, JSONObject msg) { return true; } // public void afterOnMessageReceived(MessageHeader h, JSONObject msg) {} // // // public boolean beforeSendMessageToActor(String actorID, JSONObject msg) { return beforeSendMessage(msg); } // public boolean beforeSendMessageToRole(String role, JSONObject msg) { return beforeSendMessage(msg); } // public boolean beforeSendMessageToSession(JSONObject msg) { return beforeSendMessage(msg); } // // /** // * Convenience method to which, by default, all message sending methods call through. // * @param msg // * @return // */ // public boolean beforeSendMessage(JSONObject msg) { return true; } // //public boolean afterSendMessage(Header h, Message msg) {} // // /** // * Called before an actor joins an activity. // * Returning false aborts the attempted join. // */ // public boolean beforeActivityJoin() { // return true; // } // // public void afterActivityJoin() { // // } // // /** // * Called before an actor joins an activity. // * Returning false aborts the attempted join. // */ // public boolean beforeActivityCreate() { // return true; // } // // public void afterActivityCreate() { // // } // // // //public void beforeGetActivityScript(); // // /** // * Returns an integer priority for this Extra. // * Lower priority means closer to switchboard; // * Higher means closer to actor. // */ // public Integer getPriority() { return 20; } // // public void test() { // JunctionActor actor = // new JunctionActor("unittest") { // @Override // public void onMessageReceived(MessageHeader header, JSONObject message) { // System.out.println(message.toString()); // } // // @Override // public List<JunctionExtra> getInitialExtras() { // List<JunctionExtra> extras = new ArrayList<JunctionExtra>(); // extras.add(JunctionExtra.this); // return extras; // } // }; // // try { // // todo: registeredextras here // SwitchboardConfig config = new XMPPSwitchboardConfig("prpl.stanford.edu"); // JunctionMaker.getInstance(config).newJunction(new URI("junction://prpl.stanford.edu/junit-test"), actor); // synchronized(this) { // this.wait(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // }
import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionExtra; import edu.stanford.junction.api.messaging.MessageHeader;
/* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.extra; /** * Handles internal System requests. This may include handover to OOB-transport * (or, at least, serves as an example for how to do OOB transport) * @author bjdodson * */ public class JXSystem extends JunctionExtra { protected static final String JX_SYSTEM_NS = "JXSYSTEMMSG"; public JXSystem() { } @Override public boolean beforeSendMessage(JSONObject msg) { // TODO: if message has JXSYSTEMMSG flag, don't allow. return super.beforeSendMessage(msg); } @Override
// Path: src/main/java/edu/stanford/junction/api/activity/JunctionExtra.java // public abstract class JunctionExtra { // JunctionActor mParent=null; // // /** // * Provides access to the associated JunctionActor. // * @return // */ // public final JunctionActor getActor() { // return mParent; // } // // /** // * This method should only be called internally. // * @param actor // */ // public void setActor(JunctionActor actor) { // mParent=actor; // } // // /** // * Update the parameters that will be sent in an invitation // */ // public void updateInvitationParameters(Map<String,String>params) { // // } // // /** // * Returns true if the normal event handling should proceed; // * Return false to stop cascading. // */ // public boolean beforeOnMessageReceived(MessageHeader h, JSONObject msg) { return true; } // public void afterOnMessageReceived(MessageHeader h, JSONObject msg) {} // // // public boolean beforeSendMessageToActor(String actorID, JSONObject msg) { return beforeSendMessage(msg); } // public boolean beforeSendMessageToRole(String role, JSONObject msg) { return beforeSendMessage(msg); } // public boolean beforeSendMessageToSession(JSONObject msg) { return beforeSendMessage(msg); } // // /** // * Convenience method to which, by default, all message sending methods call through. // * @param msg // * @return // */ // public boolean beforeSendMessage(JSONObject msg) { return true; } // //public boolean afterSendMessage(Header h, Message msg) {} // // /** // * Called before an actor joins an activity. // * Returning false aborts the attempted join. // */ // public boolean beforeActivityJoin() { // return true; // } // // public void afterActivityJoin() { // // } // // /** // * Called before an actor joins an activity. // * Returning false aborts the attempted join. // */ // public boolean beforeActivityCreate() { // return true; // } // // public void afterActivityCreate() { // // } // // // //public void beforeGetActivityScript(); // // /** // * Returns an integer priority for this Extra. // * Lower priority means closer to switchboard; // * Higher means closer to actor. // */ // public Integer getPriority() { return 20; } // // public void test() { // JunctionActor actor = // new JunctionActor("unittest") { // @Override // public void onMessageReceived(MessageHeader header, JSONObject message) { // System.out.println(message.toString()); // } // // @Override // public List<JunctionExtra> getInitialExtras() { // List<JunctionExtra> extras = new ArrayList<JunctionExtra>(); // extras.add(JunctionExtra.this); // return extras; // } // }; // // try { // // todo: registeredextras here // SwitchboardConfig config = new XMPPSwitchboardConfig("prpl.stanford.edu"); // JunctionMaker.getInstance(config).newJunction(new URI("junction://prpl.stanford.edu/junit-test"), actor); // synchronized(this) { // this.wait(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // Path: src/main/java/edu/stanford/junction/api/messaging/MessageHeader.java // public class MessageHeader { // private Junction jx; // private JSONObject message; // public String from; // // public MessageHeader(Junction jx, JSONObject message, String from) { // this.jx=jx; // this.message=message; // this.from=from; // } // // // public MessageTarget getReplyTarget() { // if (message.has(Junction.NS_JX)) { // JSONObject h = message.optJSONObject(Junction.NS_JX); // if (h.has("replyTo")) { // return MessageTargetFactory.getInstance(jx).getTarget(h.optString("replyTo")); // } // } // // return MessageTargetFactory.getInstance(jx).getTarget("actor:"+from); // } // // public String getSender() { // return from; // } // // public Junction getJunction() { return jx; } // } // Path: src/main/java/edu/stanford/junction/extra/JXSystem.java import org.json.JSONObject; import edu.stanford.junction.api.activity.JunctionExtra; import edu.stanford.junction.api.messaging.MessageHeader; /* * Copyright (C) 2010 Stanford University * * 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 edu.stanford.junction.extra; /** * Handles internal System requests. This may include handover to OOB-transport * (or, at least, serves as an example for how to do OOB transport) * @author bjdodson * */ public class JXSystem extends JunctionExtra { protected static final String JX_SYSTEM_NS = "JXSYSTEMMSG"; public JXSystem() { } @Override public boolean beforeSendMessage(JSONObject msg) { // TODO: if message has JXSYSTEMMSG flag, don't allow. return super.beforeSendMessage(msg); } @Override
public boolean beforeOnMessageReceived(MessageHeader h, JSONObject msg) {
MLstate/opa-eclipse-plugin
src/opaide/editors/wizard/OpaNewProjectWizard.java
// Path: src/opaide/natures/OpaProjectNature.java // public class OpaProjectNature implements IProjectNature { // // public static final String NATURE_ID = "opaide.natures.OpaProjectNature.id"; //$NON-NLS-1$ // // private IProject project; // // @Override // public void configure() throws CoreException { // // TODO Auto-generated method stub // assert(false); // } // // @Override // public void deconfigure() throws CoreException { // // TODO Auto-generated method stub // // } // // @Override // public IProject getProject() { // return project; // } // // @Override // public void setProject(IProject project) { // this.project = project; // System.out.println("ProjectNature.setProject()"); // } // // }
import opaide.natures.OpaProjectNature; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.jdt.debug.ui.launchConfigurations.JavaMainTab; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.*; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
package opaide.editors.wizard; public class OpaNewProjectWizard extends Wizard implements INewWizard, IExecutableExtension { private BasicNewProjectResourceWizard basicWizard; //private JavaMainTab j = new org.eclipse.jdt.debug.ui.launchConfigurations.JavaMainTab(); public OpaNewProjectWizard() { super(); this.basicWizard = new BasicNewProjectResourceWizard(); } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { basicWizard.init(workbench, selection); basicWizard.addPages(); for (IWizardPage p : basicWizard.getPages()) { addPage(p); System.out.println("OpaNewWizard.init()"); } } @Override public boolean performFinish() { basicWizard.setContainer(this.getContainer()); if (basicWizard.performFinish()) { //IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = basicWizard.getNewProject(); try { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds () ; String[] newNatures = new String[natures.length + 1] ; System.arraycopy (natures, 0, newNatures, 1, natures.length) ;
// Path: src/opaide/natures/OpaProjectNature.java // public class OpaProjectNature implements IProjectNature { // // public static final String NATURE_ID = "opaide.natures.OpaProjectNature.id"; //$NON-NLS-1$ // // private IProject project; // // @Override // public void configure() throws CoreException { // // TODO Auto-generated method stub // assert(false); // } // // @Override // public void deconfigure() throws CoreException { // // TODO Auto-generated method stub // // } // // @Override // public IProject getProject() { // return project; // } // // @Override // public void setProject(IProject project) { // this.project = project; // System.out.println("ProjectNature.setProject()"); // } // // } // Path: src/opaide/editors/wizard/OpaNewProjectWizard.java import opaide.natures.OpaProjectNature; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.jdt.debug.ui.launchConfigurations.JavaMainTab; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.*; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; package opaide.editors.wizard; public class OpaNewProjectWizard extends Wizard implements INewWizard, IExecutableExtension { private BasicNewProjectResourceWizard basicWizard; //private JavaMainTab j = new org.eclipse.jdt.debug.ui.launchConfigurations.JavaMainTab(); public OpaNewProjectWizard() { super(); this.basicWizard = new BasicNewProjectResourceWizard(); } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { basicWizard.init(workbench, selection); basicWizard.addPages(); for (IWizardPage p : basicWizard.getPages()) { addPage(p); System.out.println("OpaNewWizard.init()"); } } @Override public boolean performFinish() { basicWizard.setContainer(this.getContainer()); if (basicWizard.performFinish()) { //IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = basicWizard.getNewProject(); try { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds () ; String[] newNatures = new String[natures.length + 1] ; System.arraycopy (natures, 0, newNatures, 1, natures.length) ;
newNatures[0] = OpaProjectNature.NATURE_ID;
MLstate/opa-eclipse-plugin
src/opaide/editors/opasrc/OpaDocumentProvider.java
// Path: src/opaide/editors/opasrc/OpaPartitioner.java // public enum OPA_PARTITION { // OPA_STRING { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new MultiLineRule("\"", "\"", token, '\\'); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaStringScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(64, 144, 225), new FontData("Georgia", 10, SWT.ITALIC)); // } // }, // OPA_COMMENT_LINE { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new EndOfLineRule("//", token); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaCommentLineScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(63, 127, 95), new FontData("Serif", 10, TextAttribute.STRIKETHROUGH)); // } // }, // OPA_COMMENT_BLOCK { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new MultiLineRule("/*", "*/", token); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaCommentBlockScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(63, 95, 191), createDefaultFontData(SWT.NORMAL)); // } // }; // // @Override // public String toString() { // return this.getClass().getCanonicalName() + "." + super.toString(); // } // // public String getContentType() { // return String.format("__%s_%s", OPA_PARTITION.class.getName(), this.name()); // } // // private static List<String> contentTypes; // public static List<String> getContentTypes() { // if (contentTypes == null) { // List<String> result = new ArrayList<String>(); // for (OPA_PARTITION p : OPA_PARTITION.values()) // result.add(p.getContentType()); // contentTypes = result; // } // return contentTypes; // } // // public abstract IPredicateRule getPredicateRule(); // public abstract ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider); // public abstract SavedTextAttribute getTextAttribute(); // // private static FontData createDefaultFontData(int style) { // return new FontData("Monospace", 10, style); // } // // };
import java.util.List; import opaide.editors.opasrc.OpaPartitioner.OPA_PARTITION; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.editors.text.FileDocumentProvider; import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
package opaide.editors.opasrc; public class OpaDocumentProvider extends FileDocumentProvider { protected IDocument createDocument(Object element) throws CoreException { IDocument document = super.createDocument(element); if (document != null) {
// Path: src/opaide/editors/opasrc/OpaPartitioner.java // public enum OPA_PARTITION { // OPA_STRING { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new MultiLineRule("\"", "\"", token, '\\'); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaStringScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(64, 144, 225), new FontData("Georgia", 10, SWT.ITALIC)); // } // }, // OPA_COMMENT_LINE { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new EndOfLineRule("//", token); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaCommentLineScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(63, 127, 95), new FontData("Serif", 10, TextAttribute.STRIKETHROUGH)); // } // }, // OPA_COMMENT_BLOCK { // @Override // public IPredicateRule getPredicateRule() { // IToken token = new Token(this.getContentType()); // return new MultiLineRule("/*", "*/", token); // } // // @Override // public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { // return new OpaCommentBlockScanner(styleProvider); // } // // @Override // public SavedTextAttribute getTextAttribute() { // return new SavedTextAttribute(new RGB(63, 95, 191), createDefaultFontData(SWT.NORMAL)); // } // }; // // @Override // public String toString() { // return this.getClass().getCanonicalName() + "." + super.toString(); // } // // public String getContentType() { // return String.format("__%s_%s", OPA_PARTITION.class.getName(), this.name()); // } // // private static List<String> contentTypes; // public static List<String> getContentTypes() { // if (contentTypes == null) { // List<String> result = new ArrayList<String>(); // for (OPA_PARTITION p : OPA_PARTITION.values()) // result.add(p.getContentType()); // contentTypes = result; // } // return contentTypes; // } // // public abstract IPredicateRule getPredicateRule(); // public abstract ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider); // public abstract SavedTextAttribute getTextAttribute(); // // private static FontData createDefaultFontData(int style) { // return new FontData("Monospace", 10, style); // } // // }; // Path: src/opaide/editors/opasrc/OpaDocumentProvider.java import java.util.List; import opaide.editors.opasrc.OpaPartitioner.OPA_PARTITION; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.editors.text.FileDocumentProvider; import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; package opaide.editors.opasrc; public class OpaDocumentProvider extends FileDocumentProvider { protected IDocument createDocument(Object element) throws CoreException { IDocument document = super.createDocument(element); if (document != null) {
List<String> tmp = OPA_PARTITION.getContentTypes();
MLstate/opa-eclipse-plugin
src/opaide/editors/opasrc/OpaPartitioner.java
// Path: src/opaide/preferences/OpaPreferencesInitializer.java // public class OpaPreferencesInitializer extends AbstractPreferenceInitializer { // // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // // private static String suffix_font_data = "_FONTDATA"; // private static String suffix_color = "_COLOR"; // // private void setDefaultTextAttribute(String parent, RGB color, FontData font) { // PreferenceConverter.setDefault(store, parent+suffix_color, color); // PreferenceConverter.setDefault(store, parent+suffix_font_data, font); // } // // private SavedTextAttribute readSavedTextAttribute(String parent) { // RGB c = PreferenceConverter.getColor(store, parent+suffix_color); // FontData fd = PreferenceConverter.getFontData(store, parent+suffix_font_data); // /*System.out.println("PreferencesInitializer.readSavedTextAttribute()" + " reading style=" + fd.getStyle() + " for " + parent);*/ // return new SavedTextAttribute(c, fd); // } // // private static IPreferenceStore store; // // public OpaPreferencesInitializer() { // if (store == null) { // IPreferenceStore store = OpaIdePlugin.getDefault().getPreferenceStore(); // OpaPreferencesInitializer.store = store; // } // } // // @Override // public void initializeDefaultPreferences() { // // //store.addPropertyChangeListener(this); // // //store.setDefault(name, "opa"); // store.setDefault(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "/usr/bin/opa"); // // for (OPA_PARTITION p : OPA_PARTITION.values()) { // setDefaultTextAttribute(p.toString(), p.getTextAttribute().getColor(), p.getTextAttribute().getFontData()); // } // // for (CODE c : CODE.values()) { // setDefaultTextAttribute(c.toString(), c.getTextAttribute().getColor(), c.getTextAttribute().getFontData()); // } // // } // // public SavedTextAttribute getSavedTextAttribute(OPA_PARTITION p) { // return readSavedTextAttribute(p.toString()); // } // // public SavedTextAttribute getSavedTextAttribute(CODE c) { // return readSavedTextAttribute(c.toString()); // } // // public String getOpaCompilerPath() { // return store.getString(OpaPreferencesConstants.P_OPA_COMPILER_PATH); // } // // public String getOpaMLSTATELIBS() { // return store.getString(OpaPreferencesConstants.P_OPA_MLSTATELIBS); // } // // } // // Path: src/opaide/preferences/OpaPreferencesInitializer.java // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // }
import java.util.ArrayList; import java.util.List; import opaide.preferences.OpaPreferencesInitializer; import opaide.preferences.OpaPreferencesInitializer.SavedTextAttribute; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.*; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB;
package opaide.editors.opasrc; public class OpaPartitioner extends RuleBasedPartitionScanner { public enum OPA_PARTITION { OPA_STRING { @Override public IPredicateRule getPredicateRule() { IToken token = new Token(this.getContentType()); return new MultiLineRule("\"", "\"", token, '\\'); } @Override
// Path: src/opaide/preferences/OpaPreferencesInitializer.java // public class OpaPreferencesInitializer extends AbstractPreferenceInitializer { // // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // // private static String suffix_font_data = "_FONTDATA"; // private static String suffix_color = "_COLOR"; // // private void setDefaultTextAttribute(String parent, RGB color, FontData font) { // PreferenceConverter.setDefault(store, parent+suffix_color, color); // PreferenceConverter.setDefault(store, parent+suffix_font_data, font); // } // // private SavedTextAttribute readSavedTextAttribute(String parent) { // RGB c = PreferenceConverter.getColor(store, parent+suffix_color); // FontData fd = PreferenceConverter.getFontData(store, parent+suffix_font_data); // /*System.out.println("PreferencesInitializer.readSavedTextAttribute()" + " reading style=" + fd.getStyle() + " for " + parent);*/ // return new SavedTextAttribute(c, fd); // } // // private static IPreferenceStore store; // // public OpaPreferencesInitializer() { // if (store == null) { // IPreferenceStore store = OpaIdePlugin.getDefault().getPreferenceStore(); // OpaPreferencesInitializer.store = store; // } // } // // @Override // public void initializeDefaultPreferences() { // // //store.addPropertyChangeListener(this); // // //store.setDefault(name, "opa"); // store.setDefault(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "/usr/bin/opa"); // // for (OPA_PARTITION p : OPA_PARTITION.values()) { // setDefaultTextAttribute(p.toString(), p.getTextAttribute().getColor(), p.getTextAttribute().getFontData()); // } // // for (CODE c : CODE.values()) { // setDefaultTextAttribute(c.toString(), c.getTextAttribute().getColor(), c.getTextAttribute().getFontData()); // } // // } // // public SavedTextAttribute getSavedTextAttribute(OPA_PARTITION p) { // return readSavedTextAttribute(p.toString()); // } // // public SavedTextAttribute getSavedTextAttribute(CODE c) { // return readSavedTextAttribute(c.toString()); // } // // public String getOpaCompilerPath() { // return store.getString(OpaPreferencesConstants.P_OPA_COMPILER_PATH); // } // // public String getOpaMLSTATELIBS() { // return store.getString(OpaPreferencesConstants.P_OPA_MLSTATELIBS); // } // // } // // Path: src/opaide/preferences/OpaPreferencesInitializer.java // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // Path: src/opaide/editors/opasrc/OpaPartitioner.java import java.util.ArrayList; import java.util.List; import opaide.preferences.OpaPreferencesInitializer; import opaide.preferences.OpaPreferencesInitializer.SavedTextAttribute; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.*; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; package opaide.editors.opasrc; public class OpaPartitioner extends RuleBasedPartitionScanner { public enum OPA_PARTITION { OPA_STRING { @Override public IPredicateRule getPredicateRule() { IToken token = new Token(this.getContentType()); return new MultiLineRule("\"", "\"", token, '\\'); } @Override
public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) {
MLstate/opa-eclipse-plugin
src/opaide/editors/opasrc/OpaPartitioner.java
// Path: src/opaide/preferences/OpaPreferencesInitializer.java // public class OpaPreferencesInitializer extends AbstractPreferenceInitializer { // // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // // private static String suffix_font_data = "_FONTDATA"; // private static String suffix_color = "_COLOR"; // // private void setDefaultTextAttribute(String parent, RGB color, FontData font) { // PreferenceConverter.setDefault(store, parent+suffix_color, color); // PreferenceConverter.setDefault(store, parent+suffix_font_data, font); // } // // private SavedTextAttribute readSavedTextAttribute(String parent) { // RGB c = PreferenceConverter.getColor(store, parent+suffix_color); // FontData fd = PreferenceConverter.getFontData(store, parent+suffix_font_data); // /*System.out.println("PreferencesInitializer.readSavedTextAttribute()" + " reading style=" + fd.getStyle() + " for " + parent);*/ // return new SavedTextAttribute(c, fd); // } // // private static IPreferenceStore store; // // public OpaPreferencesInitializer() { // if (store == null) { // IPreferenceStore store = OpaIdePlugin.getDefault().getPreferenceStore(); // OpaPreferencesInitializer.store = store; // } // } // // @Override // public void initializeDefaultPreferences() { // // //store.addPropertyChangeListener(this); // // //store.setDefault(name, "opa"); // store.setDefault(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "/usr/bin/opa"); // // for (OPA_PARTITION p : OPA_PARTITION.values()) { // setDefaultTextAttribute(p.toString(), p.getTextAttribute().getColor(), p.getTextAttribute().getFontData()); // } // // for (CODE c : CODE.values()) { // setDefaultTextAttribute(c.toString(), c.getTextAttribute().getColor(), c.getTextAttribute().getFontData()); // } // // } // // public SavedTextAttribute getSavedTextAttribute(OPA_PARTITION p) { // return readSavedTextAttribute(p.toString()); // } // // public SavedTextAttribute getSavedTextAttribute(CODE c) { // return readSavedTextAttribute(c.toString()); // } // // public String getOpaCompilerPath() { // return store.getString(OpaPreferencesConstants.P_OPA_COMPILER_PATH); // } // // public String getOpaMLSTATELIBS() { // return store.getString(OpaPreferencesConstants.P_OPA_MLSTATELIBS); // } // // } // // Path: src/opaide/preferences/OpaPreferencesInitializer.java // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // }
import java.util.ArrayList; import java.util.List; import opaide.preferences.OpaPreferencesInitializer; import opaide.preferences.OpaPreferencesInitializer.SavedTextAttribute; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.*; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB;
package opaide.editors.opasrc; public class OpaPartitioner extends RuleBasedPartitionScanner { public enum OPA_PARTITION { OPA_STRING { @Override public IPredicateRule getPredicateRule() { IToken token = new Token(this.getContentType()); return new MultiLineRule("\"", "\"", token, '\\'); } @Override public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { return new OpaStringScanner(styleProvider); } @Override
// Path: src/opaide/preferences/OpaPreferencesInitializer.java // public class OpaPreferencesInitializer extends AbstractPreferenceInitializer { // // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // // private static String suffix_font_data = "_FONTDATA"; // private static String suffix_color = "_COLOR"; // // private void setDefaultTextAttribute(String parent, RGB color, FontData font) { // PreferenceConverter.setDefault(store, parent+suffix_color, color); // PreferenceConverter.setDefault(store, parent+suffix_font_data, font); // } // // private SavedTextAttribute readSavedTextAttribute(String parent) { // RGB c = PreferenceConverter.getColor(store, parent+suffix_color); // FontData fd = PreferenceConverter.getFontData(store, parent+suffix_font_data); // /*System.out.println("PreferencesInitializer.readSavedTextAttribute()" + " reading style=" + fd.getStyle() + " for " + parent);*/ // return new SavedTextAttribute(c, fd); // } // // private static IPreferenceStore store; // // public OpaPreferencesInitializer() { // if (store == null) { // IPreferenceStore store = OpaIdePlugin.getDefault().getPreferenceStore(); // OpaPreferencesInitializer.store = store; // } // } // // @Override // public void initializeDefaultPreferences() { // // //store.addPropertyChangeListener(this); // // //store.setDefault(name, "opa"); // store.setDefault(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "/usr/bin/opa"); // // for (OPA_PARTITION p : OPA_PARTITION.values()) { // setDefaultTextAttribute(p.toString(), p.getTextAttribute().getColor(), p.getTextAttribute().getFontData()); // } // // for (CODE c : CODE.values()) { // setDefaultTextAttribute(c.toString(), c.getTextAttribute().getColor(), c.getTextAttribute().getFontData()); // } // // } // // public SavedTextAttribute getSavedTextAttribute(OPA_PARTITION p) { // return readSavedTextAttribute(p.toString()); // } // // public SavedTextAttribute getSavedTextAttribute(CODE c) { // return readSavedTextAttribute(c.toString()); // } // // public String getOpaCompilerPath() { // return store.getString(OpaPreferencesConstants.P_OPA_COMPILER_PATH); // } // // public String getOpaMLSTATELIBS() { // return store.getString(OpaPreferencesConstants.P_OPA_MLSTATELIBS); // } // // } // // Path: src/opaide/preferences/OpaPreferencesInitializer.java // public static class SavedTextAttribute { // private RGB color; // private FontData fontData; // public SavedTextAttribute(RGB color, FontData fontData) { // this.color = color; // this.fontData = fontData; // } // public RGB getColor() { // return color; // } // public FontData getFontData() { // return fontData; // } // // public static TextAttribute toTextAttribute(Device device, SavedTextAttribute stattr) { // FontData fontData = stattr.getFontData(); // Font theFont = new Font(device, fontData); // Color foreground = ColorManager.getColor(stattr.getColor()); // return new TextAttribute(foreground, null, fontData.getStyle(), theFont); // } // } // Path: src/opaide/editors/opasrc/OpaPartitioner.java import java.util.ArrayList; import java.util.List; import opaide.preferences.OpaPreferencesInitializer; import opaide.preferences.OpaPreferencesInitializer.SavedTextAttribute; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.*; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; package opaide.editors.opasrc; public class OpaPartitioner extends RuleBasedPartitionScanner { public enum OPA_PARTITION { OPA_STRING { @Override public IPredicateRule getPredicateRule() { IToken token = new Token(this.getContentType()); return new MultiLineRule("\"", "\"", token, '\\'); } @Override public ITokenScanner getTokenScanner(OpaPreferencesInitializer styleProvider) { return new OpaStringScanner(styleProvider); } @Override
public SavedTextAttribute getTextAttribute() {
MLstate/opa-eclipse-plugin
src/opaide/editors/launch/configuration/OpaClassicConfigurationDelegate.java
// Path: src/opaide/editors/actions/RunACompilation.java // public class RunACompilation implements Runnable { // // private String execToCall; // private List<String> arguments; // private IProject project; // // public RunACompilation(IProject project, String execToCall, List<String> arguments) { // // this.project = project; // this.execToCall = execToCall; // this.arguments = arguments; // } // // @Override // public void run() { // System.out.println("RunACompilation.run()"); // List<String> tmp = new LinkedList<String>(); // tmp.add(execToCall); // tmp.add("--quiet"); // tmp.addAll(arguments); // ProcessBuilder pb = new ProcessBuilder(tmp); // File workingDir = new File(this.project.getLocation().toOSString()); // pb.directory(workingDir); // String direc; // if (pb.directory() == null) { direc = "?"; } else { direc = pb.directory().toString(); }; // System.out // .println("LaunchOpaCompilationActionDelegate.DoACompilation.run()" // + " in directory='" + direc + "'" // + " with command='" + Arrays.toString(pb.command().toArray()) + "'"); // System.out.flush(); // try { // Process p = pb.start(); // InputStream errorStream = p.getErrorStream(); // OpaMessagesFromStream opaErro = new OpaMessagesFromStream(project, errorStream); // opaErro.addMyEventListener(OpaIdePlugin.getDefault().getOpaMessagesBank().getOpaMessageListener()); // opaErro.run(); // p.waitFor(); // int toread = errorStream.available(); // byte[] tmp_byte = new byte[toread]; // errorStream.read(tmp_byte, 0, toread); // String cs = new String(tmp_byte); // System.out.println(cs); // OpaIdePlugin.getConsole().newMessageStream().print(cs); // // } catch (final IOException e) { // e.printStackTrace(); // // this run method will be put in a new thread, so we need this kind of stuff to avoid thread invalid access // Display.getDefault().asyncExec( new Runnable() { // public void run() { // OpaIdePlugin.getConsole().activate(); // MessageConsoleStream stream = OpaIdePlugin.getConsole().newMessageStream(); // Color previousColor = stream.getColor(); // stream.setColor(ColorManager.getColor(new RGB(255, 0, 0))); // stream.print(e.getMessage()); // }; // }); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // }
import java.io.File; import java.util.Arrays; import opaide.editors.actions.RunACompilation; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.*; import org.eclipse.debug.core.model.*;
package opaide.editors.launch.configuration; public class OpaClassicConfigurationDelegate extends LaunchConfigurationDelegate implements ILaunchConfigurationDelegate2 { @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { System.out.println("OpaExecutableConfigurationDelegate.launch()"); String workingDir = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_WORKING_DIR.toString(), ""); IProject project = null; for (IProject p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { if (p.getLocation().toOSString().equals(workingDir)) { project = p; break; } } String execToCall = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_MAIN_PROGRAM.toString(), "opa"); String arguments = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_MAIN_ARGUMENTS.toString(), ""); if (project != null) {
// Path: src/opaide/editors/actions/RunACompilation.java // public class RunACompilation implements Runnable { // // private String execToCall; // private List<String> arguments; // private IProject project; // // public RunACompilation(IProject project, String execToCall, List<String> arguments) { // // this.project = project; // this.execToCall = execToCall; // this.arguments = arguments; // } // // @Override // public void run() { // System.out.println("RunACompilation.run()"); // List<String> tmp = new LinkedList<String>(); // tmp.add(execToCall); // tmp.add("--quiet"); // tmp.addAll(arguments); // ProcessBuilder pb = new ProcessBuilder(tmp); // File workingDir = new File(this.project.getLocation().toOSString()); // pb.directory(workingDir); // String direc; // if (pb.directory() == null) { direc = "?"; } else { direc = pb.directory().toString(); }; // System.out // .println("LaunchOpaCompilationActionDelegate.DoACompilation.run()" // + " in directory='" + direc + "'" // + " with command='" + Arrays.toString(pb.command().toArray()) + "'"); // System.out.flush(); // try { // Process p = pb.start(); // InputStream errorStream = p.getErrorStream(); // OpaMessagesFromStream opaErro = new OpaMessagesFromStream(project, errorStream); // opaErro.addMyEventListener(OpaIdePlugin.getDefault().getOpaMessagesBank().getOpaMessageListener()); // opaErro.run(); // p.waitFor(); // int toread = errorStream.available(); // byte[] tmp_byte = new byte[toread]; // errorStream.read(tmp_byte, 0, toread); // String cs = new String(tmp_byte); // System.out.println(cs); // OpaIdePlugin.getConsole().newMessageStream().print(cs); // // } catch (final IOException e) { // e.printStackTrace(); // // this run method will be put in a new thread, so we need this kind of stuff to avoid thread invalid access // Display.getDefault().asyncExec( new Runnable() { // public void run() { // OpaIdePlugin.getConsole().activate(); // MessageConsoleStream stream = OpaIdePlugin.getConsole().newMessageStream(); // Color previousColor = stream.getColor(); // stream.setColor(ColorManager.getColor(new RGB(255, 0, 0))); // stream.print(e.getMessage()); // }; // }); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // } // Path: src/opaide/editors/launch/configuration/OpaClassicConfigurationDelegate.java import java.io.File; import java.util.Arrays; import opaide.editors.actions.RunACompilation; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.*; import org.eclipse.debug.core.model.*; package opaide.editors.launch.configuration; public class OpaClassicConfigurationDelegate extends LaunchConfigurationDelegate implements ILaunchConfigurationDelegate2 { @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { System.out.println("OpaExecutableConfigurationDelegate.launch()"); String workingDir = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_WORKING_DIR.toString(), ""); IProject project = null; for (IProject p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { if (p.getLocation().toOSString().equals(workingDir)) { project = p; break; } } String execToCall = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_MAIN_PROGRAM.toString(), "opa"); String arguments = configuration.getAttribute(OpaClassicLaunchConfigurationConstants.ATTR_OPA_MAIN_ARGUMENTS.toString(), ""); if (project != null) {
new RunACompilation(project, execToCall, Arrays.asList(arguments)).run();
MLstate/opa-eclipse-plugin
src/opaide/editors/messages/OpaMessageListenersList.java
// Path: src/opaide/editors/messages/ast/OpaMessage.java // public abstract class OpaMessage extends EventObject { // // private IProject project; // // /** // * // */ // private static final long serialVersionUID = -7145362729411737978L; // // public OpaMessage(Object source) { // super(source); // } // // public OpaMessage(Object source, IProject project) { // super(source); // assert(project != null); // this.project = project; // } // // public IProject getProject() { return this.project; } // }
import javax.swing.event.EventListenerList; import org.eclipse.core.commands.State; import org.eclipse.core.commands.common.EventManager; import opaide.editors.messages.ast.OpaMessage;
package opaide.editors.messages; public class OpaMessageListenersList extends EventManager { protected EventListenerList listenerList = new EventListenerList(); public void addMyEventListener(IOpaMessageListener listener) { listenerList.add(IOpaMessageListener.class, listener); } public void removeMyEventListener(IOpaMessageListener listener) { listenerList.remove(IOpaMessageListener.class, listener); }
// Path: src/opaide/editors/messages/ast/OpaMessage.java // public abstract class OpaMessage extends EventObject { // // private IProject project; // // /** // * // */ // private static final long serialVersionUID = -7145362729411737978L; // // public OpaMessage(Object source) { // super(source); // } // // public OpaMessage(Object source, IProject project) { // super(source); // assert(project != null); // this.project = project; // } // // public IProject getProject() { return this.project; } // } // Path: src/opaide/editors/messages/OpaMessageListenersList.java import javax.swing.event.EventListenerList; import org.eclipse.core.commands.State; import org.eclipse.core.commands.common.EventManager; import opaide.editors.messages.ast.OpaMessage; package opaide.editors.messages; public class OpaMessageListenersList extends EventManager { protected EventListenerList listenerList = new EventListenerList(); public void addMyEventListener(IOpaMessageListener listener) { listenerList.add(IOpaMessageListener.class, listener); } public void removeMyEventListener(IOpaMessageListener listener) { listenerList.remove(IOpaMessageListener.class, listener); }
public void fireMyEvent(OpaMessage evt) {
MLstate/opa-eclipse-plugin
src/opaide/editors/messages/ast/OpaErrorMessage.java
// Path: src/opaide/editors/messages/ast/util/OpaSrcLocation.java // public class OpaSrcLocation { // // private IResource theFile; // private Integer theLine; // private Integer leftCharacterForTheLine; // private Integer rightCharacterForTheLine; // private Integer preciseLineStart; // private Integer preciseLineCharPosStart; // private Integer preciseLineEnd; // private Integer preciseLineCharPosEnd; // private Integer globalCharStart; // private Integer globalCharEnd; // // public OpaSrcLocation(IResource theFile, Integer theLine, Integer leftCharacterForTheLine, Integer rightCharacterForTheLine, // Integer preciseLineStart, Integer preciseLineCharPosStart, // Integer preciseLineEnd, Integer preciseLineCharPosEnd, // Integer globalCharStart, Integer globalCharEnd) { // this.theFile = theFile; // this.theLine = theLine; this.leftCharacterForTheLine = leftCharacterForTheLine; this.rightCharacterForTheLine = rightCharacterForTheLine; // this.preciseLineStart = preciseLineStart; this.preciseLineCharPosStart = preciseLineCharPosStart; // this.preciseLineEnd = preciseLineEnd; this.preciseLineCharPosEnd = preciseLineCharPosEnd; // this.globalCharStart = globalCharStart; this.globalCharEnd = globalCharEnd; // } // // public IResource getTheFile() { // return theFile; // } // // public Integer getTheLine() { // return theLine; // } // // public Integer getLeftCharacterForTheLine() { // return leftCharacterForTheLine; // } // // public Integer getRightCharacterForTheLine() { // return rightCharacterForTheLine; // } // // public Integer getPreciseLineStart() { // return preciseLineStart; // } // // public Integer getPreciseLineCharPosStart() { // return preciseLineCharPosStart; // } // // public Integer getPreciseLineEnd() { // return preciseLineEnd; // } // // public Integer getPreciseLineCharPosEnd() { // return preciseLineCharPosEnd; // } // // public Integer getGlobalCharStart() { // return globalCharStart; // } // // public Integer getGlobalCharEnd() { // return globalCharEnd; // } // }
import opaide.editors.messages.ast.util.OpaSrcLocation; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource;
package opaide.editors.messages.ast; public class OpaErrorMessage extends OpaMessage { /** * */ private static final long serialVersionUID = 3665188292153986669L; private String errorMsg;
// Path: src/opaide/editors/messages/ast/util/OpaSrcLocation.java // public class OpaSrcLocation { // // private IResource theFile; // private Integer theLine; // private Integer leftCharacterForTheLine; // private Integer rightCharacterForTheLine; // private Integer preciseLineStart; // private Integer preciseLineCharPosStart; // private Integer preciseLineEnd; // private Integer preciseLineCharPosEnd; // private Integer globalCharStart; // private Integer globalCharEnd; // // public OpaSrcLocation(IResource theFile, Integer theLine, Integer leftCharacterForTheLine, Integer rightCharacterForTheLine, // Integer preciseLineStart, Integer preciseLineCharPosStart, // Integer preciseLineEnd, Integer preciseLineCharPosEnd, // Integer globalCharStart, Integer globalCharEnd) { // this.theFile = theFile; // this.theLine = theLine; this.leftCharacterForTheLine = leftCharacterForTheLine; this.rightCharacterForTheLine = rightCharacterForTheLine; // this.preciseLineStart = preciseLineStart; this.preciseLineCharPosStart = preciseLineCharPosStart; // this.preciseLineEnd = preciseLineEnd; this.preciseLineCharPosEnd = preciseLineCharPosEnd; // this.globalCharStart = globalCharStart; this.globalCharEnd = globalCharEnd; // } // // public IResource getTheFile() { // return theFile; // } // // public Integer getTheLine() { // return theLine; // } // // public Integer getLeftCharacterForTheLine() { // return leftCharacterForTheLine; // } // // public Integer getRightCharacterForTheLine() { // return rightCharacterForTheLine; // } // // public Integer getPreciseLineStart() { // return preciseLineStart; // } // // public Integer getPreciseLineCharPosStart() { // return preciseLineCharPosStart; // } // // public Integer getPreciseLineEnd() { // return preciseLineEnd; // } // // public Integer getPreciseLineCharPosEnd() { // return preciseLineCharPosEnd; // } // // public Integer getGlobalCharStart() { // return globalCharStart; // } // // public Integer getGlobalCharEnd() { // return globalCharEnd; // } // } // Path: src/opaide/editors/messages/ast/OpaErrorMessage.java import opaide.editors.messages.ast.util.OpaSrcLocation; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; package opaide.editors.messages.ast; public class OpaErrorMessage extends OpaMessage { /** * */ private static final long serialVersionUID = 3665188292153986669L; private String errorMsg;
private OpaSrcLocation srcLocation;
MLstate/opa-eclipse-plugin
src/opaide/preferences/OpaWorkbenchPreferencePage.java
// Path: src/opaide/OpaIdePlugin.java // public class OpaIdePlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "opaide"; //$NON-NLS-1$ // // // The shared instance // private static OpaIdePlugin plugin; // private static MessageConsole console; // // private OpaBinCompiler opaBinCompiler; // private OpaPreferencesInitializer prefs; // // /** // * The constructor // */ // public OpaIdePlugin() { // } // // /* // * (non-Javadoc) // * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) // */ // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // this.prefs = new OpaPreferencesInitializer(); // this.opaBinCompiler = new OpaBinCompiler(this.prefs); // // IConsoleManager conMan = ConsolePlugin.getDefault().getConsoleManager(); // MessageConsole myConsole = new MessageConsole("Opa output", null); // conMan.addConsoles(new IConsole[]{ myConsole }); // this.console = myConsole; // // } // // /* // * (non-Javadoc) // * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // console = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static OpaIdePlugin getDefault() { // return plugin; // } // // public OpaBinCompiler getBinCompiler() { // return opaBinCompiler; // } // // public OpaPreferencesInitializer getPrefs() { // return prefs; // } // // public static MessageConsole getConsole() { // return console; // } // // private OpaMessagesBank myOpaMessagesBank = new OpaMessagesBank(); // public OpaMessagesBank getOpaMessagesBank(){ return myOpaMessagesBank; }; // // public Display getDisplay() { // Display display = Display.getCurrent(); // //may be null if outside the UI thread // if (display == null) { // display = Display.getDefault(); // } // return display; // } // // }
import java.io.File; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationSelectionDialog; import org.eclipse.debug.internal.ui.launchConfigurations.SelectLaunchModesDialog; import org.eclipse.debug.internal.ui.sourcelookup.browsers.ProjectSourceContainerBrowser; import org.eclipse.debug.internal.ui.sourcelookup.browsers.ProjectSourceContainerDialog; import org.eclipse.jdt.internal.debug.ui.actions.ProjectSelectionDialog; import org.eclipse.jface.preference.*; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.IWorkbench; import opaide.OpaIdePlugin;
package opaide.preferences; public class OpaWorkbenchPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private IWorkbench workbench; public OpaWorkbenchPreferencePage() { super(org.eclipse.jface.preference.FieldEditorPreferencePage.GRID); } /** * Creates the field editors. Field editors are abstractions of * the common GUI blocks needed to manipulate various types * of preferences. Each field editor knows how to save and * restore itself. */ public void createFieldEditors() { System.out.println("WorkbenchPreferencePage1.createFieldEditors()"); /* IProject[] ps = ResourcesPlugin.getWorkspace().getRoot().getProjects(); LaunchConfigurationSelectionDialog tmp = new LaunchConfigurationSelectionDialog(this.getShell(), ps); tmp.open(); */ ExecutableFileFieldEditor opaFileFieldEditor = new ExecutableFileFieldEditor(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "Opa compiler:", true, FileFieldEditor.VALIDATE_ON_KEY_STROKE, getFieldEditorParent()); addField(opaFileFieldEditor); DirectoryFieldEditor opaMLLIBSFieldEditor = new DirectoryFieldEditor(OpaPreferencesConstants.P_OPA_MLSTATELIBS, "MLSTATELIBS env variable:", getFieldEditorParent()); opaMLLIBSFieldEditor.setEmptyStringAllowed(false); opaMLLIBSFieldEditor.setValidateStrategy(DirectoryFieldEditor.VALIDATE_ON_KEY_STROKE); addField(opaMLLIBSFieldEditor); } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { this.workbench = workbench; setDescription("The preferences page of Opa");
// Path: src/opaide/OpaIdePlugin.java // public class OpaIdePlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "opaide"; //$NON-NLS-1$ // // // The shared instance // private static OpaIdePlugin plugin; // private static MessageConsole console; // // private OpaBinCompiler opaBinCompiler; // private OpaPreferencesInitializer prefs; // // /** // * The constructor // */ // public OpaIdePlugin() { // } // // /* // * (non-Javadoc) // * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) // */ // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // this.prefs = new OpaPreferencesInitializer(); // this.opaBinCompiler = new OpaBinCompiler(this.prefs); // // IConsoleManager conMan = ConsolePlugin.getDefault().getConsoleManager(); // MessageConsole myConsole = new MessageConsole("Opa output", null); // conMan.addConsoles(new IConsole[]{ myConsole }); // this.console = myConsole; // // } // // /* // * (non-Javadoc) // * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // console = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static OpaIdePlugin getDefault() { // return plugin; // } // // public OpaBinCompiler getBinCompiler() { // return opaBinCompiler; // } // // public OpaPreferencesInitializer getPrefs() { // return prefs; // } // // public static MessageConsole getConsole() { // return console; // } // // private OpaMessagesBank myOpaMessagesBank = new OpaMessagesBank(); // public OpaMessagesBank getOpaMessagesBank(){ return myOpaMessagesBank; }; // // public Display getDisplay() { // Display display = Display.getCurrent(); // //may be null if outside the UI thread // if (display == null) { // display = Display.getDefault(); // } // return display; // } // // } // Path: src/opaide/preferences/OpaWorkbenchPreferencePage.java import java.io.File; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationSelectionDialog; import org.eclipse.debug.internal.ui.launchConfigurations.SelectLaunchModesDialog; import org.eclipse.debug.internal.ui.sourcelookup.browsers.ProjectSourceContainerBrowser; import org.eclipse.debug.internal.ui.sourcelookup.browsers.ProjectSourceContainerDialog; import org.eclipse.jdt.internal.debug.ui.actions.ProjectSelectionDialog; import org.eclipse.jface.preference.*; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.IWorkbench; import opaide.OpaIdePlugin; package opaide.preferences; public class OpaWorkbenchPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private IWorkbench workbench; public OpaWorkbenchPreferencePage() { super(org.eclipse.jface.preference.FieldEditorPreferencePage.GRID); } /** * Creates the field editors. Field editors are abstractions of * the common GUI blocks needed to manipulate various types * of preferences. Each field editor knows how to save and * restore itself. */ public void createFieldEditors() { System.out.println("WorkbenchPreferencePage1.createFieldEditors()"); /* IProject[] ps = ResourcesPlugin.getWorkspace().getRoot().getProjects(); LaunchConfigurationSelectionDialog tmp = new LaunchConfigurationSelectionDialog(this.getShell(), ps); tmp.open(); */ ExecutableFileFieldEditor opaFileFieldEditor = new ExecutableFileFieldEditor(OpaPreferencesConstants.P_OPA_COMPILER_PATH, "Opa compiler:", true, FileFieldEditor.VALIDATE_ON_KEY_STROKE, getFieldEditorParent()); addField(opaFileFieldEditor); DirectoryFieldEditor opaMLLIBSFieldEditor = new DirectoryFieldEditor(OpaPreferencesConstants.P_OPA_MLSTATELIBS, "MLSTATELIBS env variable:", getFieldEditorParent()); opaMLLIBSFieldEditor.setEmptyStringAllowed(false); opaMLLIBSFieldEditor.setValidateStrategy(DirectoryFieldEditor.VALIDATE_ON_KEY_STROKE); addField(opaMLLIBSFieldEditor); } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { this.workbench = workbench; setDescription("The preferences page of Opa");
setPreferenceStore(OpaIdePlugin.getDefault().getPreferenceStore());
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/modules/AppModule.java
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.app.App;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.modules; /** * Created by 程序亦非猿 on 16/10/18. */ @Module public class AppModule {
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/di/modules/AppModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.app.App; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.modules; /** * Created by 程序亦非猿 on 16/10/18. */ @Module public class AppModule {
private final App mApp;
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/module/gank/ReturnTopEvent.java // public class ReturnTopEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/OPRecyclerView.java // public class OpRecyclerView extends RecyclerView implements OpOnScrollListener.OnBottomListener { // // private static final String TAG = "OPRecyclerView"; // // // private OpOnScrollListener mOpOnScrollListener; // public OpRecyclerView(Context context) { // super(context); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // private void init() { // } // // @Override // public void setLayoutManager(LayoutManager layout) { // if (null == mOpOnScrollListener) { // mOpOnScrollListener = new OpOnScrollListener(layout, this); // addOnScrollListener(mOpOnScrollListener); // } // super.setLayoutManager(layout); // } // // @Override // public void setAdapter(Adapter adapter) { // // TODO: 16/7/28 wrap the adapter // super.setAdapter(adapter); // } // // @Override // public void onBottom() { // Log.d(TAG, "onBottom: "); // if (null != mOnLoadMoreListener) { // mOnLoadMoreListener.onLoadMore(); // } // } // // // public void setLoadMoreComplete() { // if (null != mOpOnScrollListener) { // mOpOnScrollListener.setLoadMoreComplete(); // } // } // // private OnLoadMoreListener mOnLoadMoreListener; // // public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { // mOnLoadMoreListener = onLoadMoreListener; // } // // public interface OnLoadMoreListener { // void onLoadMore(); // } // // }
import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.gank.ReturnTopEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; import me.yifeiyuan.climb.ui.view.OpRecyclerView; import rx.Subscriber; import rx.Subscription; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import org.greenrobot.eventbus.Subscribe;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * encapsulate refresh & loadmore */ public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { @Bind(R.id.rv) protected OpRecyclerView mRecyclerView; @Bind(R.id.refresh) protected SwipeRefreshLayout mSwipeRefreshLayout; @Nullable @Bind(R.id.fab) protected FloatingActionButton mFab; @Nullable @Bind(R.id.col) protected CoordinatorLayout mCol; /** * 页码 */ protected int mCurrPage = 1; @Override protected int getLayoutId() { return R.layout.base_refresh_fragment; } /** * 处理公用的view的初始化 * * @param savedInstanceState */ @CallSuper @Override protected void initView(@Nullable Bundle savedInstanceState) {
// Path: app/src/main/java/me/yifeiyuan/climb/module/gank/ReturnTopEvent.java // public class ReturnTopEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/OPRecyclerView.java // public class OpRecyclerView extends RecyclerView implements OpOnScrollListener.OnBottomListener { // // private static final String TAG = "OPRecyclerView"; // // // private OpOnScrollListener mOpOnScrollListener; // public OpRecyclerView(Context context) { // super(context); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // private void init() { // } // // @Override // public void setLayoutManager(LayoutManager layout) { // if (null == mOpOnScrollListener) { // mOpOnScrollListener = new OpOnScrollListener(layout, this); // addOnScrollListener(mOpOnScrollListener); // } // super.setLayoutManager(layout); // } // // @Override // public void setAdapter(Adapter adapter) { // // TODO: 16/7/28 wrap the adapter // super.setAdapter(adapter); // } // // @Override // public void onBottom() { // Log.d(TAG, "onBottom: "); // if (null != mOnLoadMoreListener) { // mOnLoadMoreListener.onLoadMore(); // } // } // // // public void setLoadMoreComplete() { // if (null != mOpOnScrollListener) { // mOpOnScrollListener.setLoadMoreComplete(); // } // } // // private OnLoadMoreListener mOnLoadMoreListener; // // public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { // mOnLoadMoreListener = onLoadMoreListener; // } // // public interface OnLoadMoreListener { // void onLoadMore(); // } // // } // Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.gank.ReturnTopEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; import me.yifeiyuan.climb.ui.view.OpRecyclerView; import rx.Subscriber; import rx.Subscription; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import org.greenrobot.eventbus.Subscribe; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * encapsulate refresh & loadmore */ public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { @Bind(R.id.rv) protected OpRecyclerView mRecyclerView; @Bind(R.id.refresh) protected SwipeRefreshLayout mSwipeRefreshLayout; @Nullable @Bind(R.id.fab) protected FloatingActionButton mFab; @Nullable @Bind(R.id.col) protected CoordinatorLayout mCol; /** * 页码 */ protected int mCurrPage = 1; @Override protected int getLayoutId() { return R.layout.base_refresh_fragment; } /** * 处理公用的view的初始化 * * @param savedInstanceState */ @CallSuper @Override protected void initView(@Nullable Bundle savedInstanceState) {
OldDriver.getIns().register(this);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/module/gank/ReturnTopEvent.java // public class ReturnTopEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/OPRecyclerView.java // public class OpRecyclerView extends RecyclerView implements OpOnScrollListener.OnBottomListener { // // private static final String TAG = "OPRecyclerView"; // // // private OpOnScrollListener mOpOnScrollListener; // public OpRecyclerView(Context context) { // super(context); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // private void init() { // } // // @Override // public void setLayoutManager(LayoutManager layout) { // if (null == mOpOnScrollListener) { // mOpOnScrollListener = new OpOnScrollListener(layout, this); // addOnScrollListener(mOpOnScrollListener); // } // super.setLayoutManager(layout); // } // // @Override // public void setAdapter(Adapter adapter) { // // TODO: 16/7/28 wrap the adapter // super.setAdapter(adapter); // } // // @Override // public void onBottom() { // Log.d(TAG, "onBottom: "); // if (null != mOnLoadMoreListener) { // mOnLoadMoreListener.onLoadMore(); // } // } // // // public void setLoadMoreComplete() { // if (null != mOpOnScrollListener) { // mOpOnScrollListener.setLoadMoreComplete(); // } // } // // private OnLoadMoreListener mOnLoadMoreListener; // // public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { // mOnLoadMoreListener = onLoadMoreListener; // } // // public interface OnLoadMoreListener { // void onLoadMore(); // } // // }
import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.gank.ReturnTopEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; import me.yifeiyuan.climb.ui.view.OpRecyclerView; import rx.Subscriber; import rx.Subscription; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import org.greenrobot.eventbus.Subscribe;
this.isForce = isForce; this.isRefresh = isRefresh; } @Override public void onCompleted() { setRefreshing(false); } @Override public void onError(Throwable e) { setRefreshing(false); if (mCurrPage != 1) { setLoadMoreComplete(); } Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); snackbar.setAction("重试", v -> { mCurrPage--; requestData(isForce, isRefresh); }); snackbar.show(); } @Override public void onNext(T t) { } } @Subscribe
// Path: app/src/main/java/me/yifeiyuan/climb/module/gank/ReturnTopEvent.java // public class ReturnTopEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/OPRecyclerView.java // public class OpRecyclerView extends RecyclerView implements OpOnScrollListener.OnBottomListener { // // private static final String TAG = "OPRecyclerView"; // // // private OpOnScrollListener mOpOnScrollListener; // public OpRecyclerView(Context context) { // super(context); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public OpRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // private void init() { // } // // @Override // public void setLayoutManager(LayoutManager layout) { // if (null == mOpOnScrollListener) { // mOpOnScrollListener = new OpOnScrollListener(layout, this); // addOnScrollListener(mOpOnScrollListener); // } // super.setLayoutManager(layout); // } // // @Override // public void setAdapter(Adapter adapter) { // // TODO: 16/7/28 wrap the adapter // super.setAdapter(adapter); // } // // @Override // public void onBottom() { // Log.d(TAG, "onBottom: "); // if (null != mOnLoadMoreListener) { // mOnLoadMoreListener.onLoadMore(); // } // } // // // public void setLoadMoreComplete() { // if (null != mOpOnScrollListener) { // mOpOnScrollListener.setLoadMoreComplete(); // } // } // // private OnLoadMoreListener mOnLoadMoreListener; // // public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { // mOnLoadMoreListener = onLoadMoreListener; // } // // public interface OnLoadMoreListener { // void onLoadMore(); // } // // } // Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.gank.ReturnTopEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; import me.yifeiyuan.climb.ui.view.OpRecyclerView; import rx.Subscriber; import rx.Subscription; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import org.greenrobot.eventbus.Subscribe; this.isForce = isForce; this.isRefresh = isRefresh; } @Override public void onCompleted() { setRefreshing(false); } @Override public void onError(Throwable e) { setRefreshing(false); if (mCurrPage != 1) { setLoadMoreComplete(); } Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); snackbar.setAction("重试", v -> { mCurrPage--; requestData(isForce, isRefresh); }); snackbar.show(); } @Override public void onNext(T t) { } } @Subscribe
public void onReturnTop(ReturnTopEvent event) {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java
// Path: app/src/main/java/me/yifeiyuan/climb/app/Config.java // public class Config { // // // public static final String HEFENG_WEATHER = "5a6314f966f4436b80dfa8c9ea4220be"; // public static final String BAIDU_WEATHER = "8ad00b1cbcaa85ba0784b6ba07a00ac8"; // }
import me.yifeiyuan.climb.app.Config; import okhttp3.RequestBody; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Query; import rx.Observable;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/9/29. * * http://apistore.baidu.com/apiworks/servicedetail/478.html * * http://www.heweather.com/documents/ */ public interface WeatherApi { // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // @GET("https://api.heweather.com/x3/weather?") // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); @GET("http://apis.baidu.com/heweather/weather/free")
// Path: app/src/main/java/me/yifeiyuan/climb/app/Config.java // public class Config { // // // public static final String HEFENG_WEATHER = "5a6314f966f4436b80dfa8c9ea4220be"; // public static final String BAIDU_WEATHER = "8ad00b1cbcaa85ba0784b6ba07a00ac8"; // } // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java import me.yifeiyuan.climb.app.Config; import okhttp3.RequestBody; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Query; import rx.Observable; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/9/29. * * http://apistore.baidu.com/apiworks/servicedetail/478.html * * http://www.heweather.com/documents/ */ public interface WeatherApi { // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // @GET("https://api.heweather.com/x3/weather?") // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); @GET("http://apis.baidu.com/heweather/weather/free")
@Headers({"apikey:"+ Config.BAIDU_WEATHER})
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/BaseFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/tools/trace/Agent.java // public class Agent { // // public static void onEvent(Context context, String eventName, String s1) { // if (enable()) { // MobclickAgent.onEvent(context, eventName, s1); // } // } // // public static void onEvent(Context context, String eventName) { // if (enable()) { // MobclickAgent.onEvent(context, eventName); // } // } // // // public static void onResume(Context context) { // if (enable()) { // MobclickAgent.onResume(context); // } // } // // public static void onPause(Context context) { // if (enable()) { // MobclickAgent.onPause(context); // } // } // // public static void onPageStart(String s) { // if (enable()) { // MobclickAgent.onPageStart(s); // } // } // // public static void onPageEnd(String s) { // if (enable()) { // MobclickAgent.onPageEnd(s); // } // } // // private static boolean enable() { // // 控制开关 // // return !BuildConfig.DEBUG; // return true; // } // }
import rx.subscriptions.CompositeSubscription; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import me.yifeiyuan.climb.tools.trace.Agent; import rx.Subscription;
mRootView = inflater.inflate(getLayoutId(), container, false); ButterKnife.bind(this, mRootView); mActivity = (BaseActivity) getActivity(); mSubscriptions = new CompositeSubscription(); Bundle args = getArguments(); if (null != args) { initArguments(args); } initData(); initView(savedInstanceState); mRootView.post(() -> requestData(false, true)); return mRootView; } protected abstract @LayoutRes int getLayoutId(); protected void initArguments(@NonNull Bundle args) { } protected abstract void initData(); protected abstract void initView(@Nullable Bundle savedInstanceState); protected abstract void requestData(boolean isForce, boolean isRefresh); @Override public void onResume() { super.onResume();
// Path: app/src/main/java/me/yifeiyuan/climb/tools/trace/Agent.java // public class Agent { // // public static void onEvent(Context context, String eventName, String s1) { // if (enable()) { // MobclickAgent.onEvent(context, eventName, s1); // } // } // // public static void onEvent(Context context, String eventName) { // if (enable()) { // MobclickAgent.onEvent(context, eventName); // } // } // // // public static void onResume(Context context) { // if (enable()) { // MobclickAgent.onResume(context); // } // } // // public static void onPause(Context context) { // if (enable()) { // MobclickAgent.onPause(context); // } // } // // public static void onPageStart(String s) { // if (enable()) { // MobclickAgent.onPageStart(s); // } // } // // public static void onPageEnd(String s) { // if (enable()) { // MobclickAgent.onPageEnd(s); // } // } // // private static boolean enable() { // // 控制开关 // // return !BuildConfig.DEBUG; // return true; // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/BaseFragment.java import rx.subscriptions.CompositeSubscription; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import me.yifeiyuan.climb.tools.trace.Agent; import rx.Subscription; mRootView = inflater.inflate(getLayoutId(), container, false); ButterKnife.bind(this, mRootView); mActivity = (BaseActivity) getActivity(); mSubscriptions = new CompositeSubscription(); Bundle args = getArguments(); if (null != args) { initArguments(args); } initData(); initView(savedInstanceState); mRootView.post(() -> requestData(false, true)); return mRootView; } protected abstract @LayoutRes int getLayoutId(); protected void initArguments(@NonNull Bundle args) { } protected abstract void initData(); protected abstract void initView(@Nullable Bundle savedInstanceState); protected abstract void requestData(boolean isForce, boolean isRefresh); @Override public void onResume() { super.onResume();
Agent.onPageStart(TAG); //统计页面
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/hook/PackageManagerHook.java
// Path: app/src/main/java/me/yifeiyuan/climb/tools/utils/ChannelUtil.java // public class ChannelUtil { // // private static final String TAG = "ChannelUtil"; // private static final String CHANNEL_KEY = "channel"; // // private static String sChannel; // // /** // * @param context // * // * @return 渠道 默认为空 // */ // public static String getChannel(Context context) { // return getChannel(context, ""); // } // // /** // * @param context // * @param defaultChannel 默认值 // * // * @return 渠道 // */ // public static String getChannel(Context context, String defaultChannel) { // //内存中获取 // if (!TextUtils.isEmpty(sChannel)) { // return sChannel; // } // //从apk中获取 // sChannel = getChannelFromApk(context, CHANNEL_KEY); // //全部获取失败 // return defaultChannel; // } // // /** // * 从apk中获取版本信息 // * // * @param context // * @param channelKey // * // * @return // */ // private static String getChannelFromApk(Context context, String channelKey) { // //从apk包中获取 // ApplicationInfo appinfo = context.getApplicationInfo(); // String sourceDir = appinfo.sourceDir; // //默认放在meta-inf/里 // String key = "META-INF/" + channelKey; // String ret = ""; // ZipFile zipfile = null; // try { // zipfile = new ZipFile(sourceDir); // Enumeration<?> entries = zipfile.entries(); // while (entries.hasMoreElements()) { // ZipEntry entry = ((ZipEntry) entries.nextElement()); // String entryName = entry.getName(); // if (entryName.startsWith(key)) { // ret = entryName; // break; // } // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (zipfile != null) { // try { // zipfile.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // String[] split = ret.split("_"); // String channel = ""; // if (split.length >= 2) { // channel = ret.substring(split[0].length() + 1); // } // Log.i(TAG, "getChannelFromApk: " + channel); // return channel; // } // }
import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.text.TextUtils; import android.util.Log; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import me.yifeiyuan.climb.tools.utils.ChannelUtil;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.hook; /** * Created by 程序亦非猿 on 16/8/22. * hook ActivityThread.sPackageManager * @see #hook * */ public class PackageManagerHook { private static String CHANNEL_KEY = "UMENG_CHANNEL"; /** * 越早 hook 越好,推荐在 attachBaseContext 调用 * @param context base */ public static void hook(Context context) { try { // 获取 activityThread Class<?> activityThreadClazz = Class.forName("android.app.ActivityThread", false, context.getClassLoader()); Method currentActivityThread = activityThreadClazz.getDeclaredMethod("currentActivityThread"); currentActivityThread.setAccessible(true); Object activityThread = currentActivityThread.invoke(null); // 获取 activityThread 的 packageManager Method getPackageManager = activityThreadClazz.getDeclaredMethod("getPackageManager"); getPackageManager.setAccessible(true); Object pkgManager = getPackageManager.invoke(activityThread);//IPackageManager$Stub$Proxy // 动态代理 Class<?> packageManagerClazz = Class.forName("android.content.pm.IPackageManager", false, context.getClassLoader()); Object pmProxy = Proxy.newProxyInstance(context.getClassLoader(), new Class[]{packageManagerClazz}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(pkgManager, args); //拦截getApplicationInfo方法 umeng 获取 CHANNEL_KEY 就是通过它 //其它的方法就让它自己过去吧 if ("getApplicationInfo".equals(method.getName())) { int mask = (int) args[1]; if (mask == PackageManager.GET_META_DATA) { ApplicationInfo appInfo = (ApplicationInfo) result; if (null != appInfo.metaData&&appInfo.metaData.containsKey(CHANNEL_KEY)) { String channel = String.valueOf(appInfo.metaData.get(CHANNEL_KEY)); Log.d("Channel before", ":"+channel);
// Path: app/src/main/java/me/yifeiyuan/climb/tools/utils/ChannelUtil.java // public class ChannelUtil { // // private static final String TAG = "ChannelUtil"; // private static final String CHANNEL_KEY = "channel"; // // private static String sChannel; // // /** // * @param context // * // * @return 渠道 默认为空 // */ // public static String getChannel(Context context) { // return getChannel(context, ""); // } // // /** // * @param context // * @param defaultChannel 默认值 // * // * @return 渠道 // */ // public static String getChannel(Context context, String defaultChannel) { // //内存中获取 // if (!TextUtils.isEmpty(sChannel)) { // return sChannel; // } // //从apk中获取 // sChannel = getChannelFromApk(context, CHANNEL_KEY); // //全部获取失败 // return defaultChannel; // } // // /** // * 从apk中获取版本信息 // * // * @param context // * @param channelKey // * // * @return // */ // private static String getChannelFromApk(Context context, String channelKey) { // //从apk包中获取 // ApplicationInfo appinfo = context.getApplicationInfo(); // String sourceDir = appinfo.sourceDir; // //默认放在meta-inf/里 // String key = "META-INF/" + channelKey; // String ret = ""; // ZipFile zipfile = null; // try { // zipfile = new ZipFile(sourceDir); // Enumeration<?> entries = zipfile.entries(); // while (entries.hasMoreElements()) { // ZipEntry entry = ((ZipEntry) entries.nextElement()); // String entryName = entry.getName(); // if (entryName.startsWith(key)) { // ret = entryName; // break; // } // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (zipfile != null) { // try { // zipfile.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // String[] split = ret.split("_"); // String channel = ""; // if (split.length >= 2) { // channel = ret.substring(split[0].length() + 1); // } // Log.i(TAG, "getChannelFromApk: " + channel); // return channel; // } // } // Path: app/src/main/java/me/yifeiyuan/climb/hook/PackageManagerHook.java import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.text.TextUtils; import android.util.Log; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import me.yifeiyuan.climb.tools.utils.ChannelUtil; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.hook; /** * Created by 程序亦非猿 on 16/8/22. * hook ActivityThread.sPackageManager * @see #hook * */ public class PackageManagerHook { private static String CHANNEL_KEY = "UMENG_CHANNEL"; /** * 越早 hook 越好,推荐在 attachBaseContext 调用 * @param context base */ public static void hook(Context context) { try { // 获取 activityThread Class<?> activityThreadClazz = Class.forName("android.app.ActivityThread", false, context.getClassLoader()); Method currentActivityThread = activityThreadClazz.getDeclaredMethod("currentActivityThread"); currentActivityThread.setAccessible(true); Object activityThread = currentActivityThread.invoke(null); // 获取 activityThread 的 packageManager Method getPackageManager = activityThreadClazz.getDeclaredMethod("getPackageManager"); getPackageManager.setAccessible(true); Object pkgManager = getPackageManager.invoke(activityThread);//IPackageManager$Stub$Proxy // 动态代理 Class<?> packageManagerClazz = Class.forName("android.content.pm.IPackageManager", false, context.getClassLoader()); Object pmProxy = Proxy.newProxyInstance(context.getClassLoader(), new Class[]{packageManagerClazz}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(pkgManager, args); //拦截getApplicationInfo方法 umeng 获取 CHANNEL_KEY 就是通过它 //其它的方法就让它自己过去吧 if ("getApplicationInfo".equals(method.getName())) { int mask = (int) args[1]; if (mask == PackageManager.GET_META_DATA) { ApplicationInfo appInfo = (ApplicationInfo) result; if (null != appInfo.metaData&&appInfo.metaData.containsKey(CHANNEL_KEY)) { String channel = String.valueOf(appInfo.metaData.get(CHANNEL_KEY)); Log.d("Channel before", ":"+channel);
String newChannel = ChannelUtil.getChannel(context);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/BaseActivity.java
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/di/components/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // // App app(); // // Api api(); // } // // Path: swipeback/src/main/java/me/yifeiyuan/swipeback/SwipeBackActivity.java // public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase { // private SwipeBackActivityHelper mHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mHelper = new SwipeBackActivityHelper(this); // mHelper.onActivityCreate(); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // mHelper.onPostCreate(); // } // // @Override // public View findViewById(int id) { // View v = super.findViewById(id); // if (v == null && mHelper != null) // return mHelper.findViewById(id); // return v; // } // // @Override // public SwipeBackLayout getSwipeBackLayout() { // return mHelper.getSwipeBackLayout(); // } // // @Override // public void setSwipeBackEnable(boolean enable) { // getSwipeBackLayout().setEnableGesture(enable); // } // // @Override // public void scrollToFinishActivity() { // Utils.convertActivityToTranslucent(this); // getSwipeBackLayout().scrollToFinishActivity(); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.app.App; import me.yifeiyuan.climb.di.components.AppComponent; import me.yifeiyuan.swipeback.SwipeBackActivity;
} return super.onOptionsItemSelected(item); } /** * 添加fragment * * @param frag 要添加的frag * @param tag frag的tag * @see #getContainerViewId() */ protected void addFragment(@NonNull Fragment frag, @NonNull String tag) { getSupportFragmentManager() .beginTransaction() .add(getContainerViewId(), frag, tag) .commitAllowingStateLoss(); } /** * * @return 存放fragment的container 的ID */ protected @IdRes int getContainerViewId() { return R.id.container; } protected final <T extends View> T find(@IdRes int id) { return (T) findViewById(id); }
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/di/components/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // // App app(); // // Api api(); // } // // Path: swipeback/src/main/java/me/yifeiyuan/swipeback/SwipeBackActivity.java // public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase { // private SwipeBackActivityHelper mHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mHelper = new SwipeBackActivityHelper(this); // mHelper.onActivityCreate(); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // mHelper.onPostCreate(); // } // // @Override // public View findViewById(int id) { // View v = super.findViewById(id); // if (v == null && mHelper != null) // return mHelper.findViewById(id); // return v; // } // // @Override // public SwipeBackLayout getSwipeBackLayout() { // return mHelper.getSwipeBackLayout(); // } // // @Override // public void setSwipeBackEnable(boolean enable) { // getSwipeBackLayout().setEnableGesture(enable); // } // // @Override // public void scrollToFinishActivity() { // Utils.convertActivityToTranslucent(this); // getSwipeBackLayout().scrollToFinishActivity(); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/BaseActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.app.App; import me.yifeiyuan.climb.di.components.AppComponent; import me.yifeiyuan.swipeback.SwipeBackActivity; } return super.onOptionsItemSelected(item); } /** * 添加fragment * * @param frag 要添加的frag * @param tag frag的tag * @see #getContainerViewId() */ protected void addFragment(@NonNull Fragment frag, @NonNull String tag) { getSupportFragmentManager() .beginTransaction() .add(getContainerViewId(), frag, tag) .commitAllowingStateLoss(); } /** * * @return 存放fragment的container 的ID */ protected @IdRes int getContainerViewId() { return R.id.container; } protected final <T extends View> T find(@IdRes int id) { return (T) findViewById(id); }
public AppComponent getAppComponent() {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/BaseActivity.java
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/di/components/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // // App app(); // // Api api(); // } // // Path: swipeback/src/main/java/me/yifeiyuan/swipeback/SwipeBackActivity.java // public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase { // private SwipeBackActivityHelper mHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mHelper = new SwipeBackActivityHelper(this); // mHelper.onActivityCreate(); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // mHelper.onPostCreate(); // } // // @Override // public View findViewById(int id) { // View v = super.findViewById(id); // if (v == null && mHelper != null) // return mHelper.findViewById(id); // return v; // } // // @Override // public SwipeBackLayout getSwipeBackLayout() { // return mHelper.getSwipeBackLayout(); // } // // @Override // public void setSwipeBackEnable(boolean enable) { // getSwipeBackLayout().setEnableGesture(enable); // } // // @Override // public void scrollToFinishActivity() { // Utils.convertActivityToTranslucent(this); // getSwipeBackLayout().scrollToFinishActivity(); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.app.App; import me.yifeiyuan.climb.di.components.AppComponent; import me.yifeiyuan.swipeback.SwipeBackActivity;
return super.onOptionsItemSelected(item); } /** * 添加fragment * * @param frag 要添加的frag * @param tag frag的tag * @see #getContainerViewId() */ protected void addFragment(@NonNull Fragment frag, @NonNull String tag) { getSupportFragmentManager() .beginTransaction() .add(getContainerViewId(), frag, tag) .commitAllowingStateLoss(); } /** * * @return 存放fragment的container 的ID */ protected @IdRes int getContainerViewId() { return R.id.container; } protected final <T extends View> T find(@IdRes int id) { return (T) findViewById(id); } public AppComponent getAppComponent() {
// Path: app/src/main/java/me/yifeiyuan/climb/app/App.java // public class App extends Application { // // private AppComponent mAppComponent; // // private static final String TAG = "Climb"; // // @Override // public void onCreate() { // super.onCreate(); // // PackageManagerHook.hook(this); // Log.d(TAG, "onCreate: " + getPackageName()); // // mAppComponent = DaggerAppComponent // .builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // // if (BuildConfig.DEBUG) { // AndroidDevMetrics.initWith(this); // } // // AppStatusManager.getInstance().init(this); // // } // // public AppComponent getAppComponent() { // return mAppComponent; // } // // @Override // protected void attachBaseContext(Context base) { // PackageManagerHook.hook(base); // super.attachBaseContext(base); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/di/components/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // // App app(); // // Api api(); // } // // Path: swipeback/src/main/java/me/yifeiyuan/swipeback/SwipeBackActivity.java // public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase { // private SwipeBackActivityHelper mHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mHelper = new SwipeBackActivityHelper(this); // mHelper.onActivityCreate(); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // mHelper.onPostCreate(); // } // // @Override // public View findViewById(int id) { // View v = super.findViewById(id); // if (v == null && mHelper != null) // return mHelper.findViewById(id); // return v; // } // // @Override // public SwipeBackLayout getSwipeBackLayout() { // return mHelper.getSwipeBackLayout(); // } // // @Override // public void setSwipeBackEnable(boolean enable) { // getSwipeBackLayout().setEnableGesture(enable); // } // // @Override // public void scrollToFinishActivity() { // Utils.convertActivityToTranslucent(this); // getSwipeBackLayout().scrollToFinishActivity(); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/BaseActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.app.App; import me.yifeiyuan.climb.di.components.AppComponent; import me.yifeiyuan.swipeback.SwipeBackActivity; return super.onOptionsItemSelected(item); } /** * 添加fragment * * @param frag 要添加的frag * @param tag frag的tag * @see #getContainerViewId() */ protected void addFragment(@NonNull Fragment frag, @NonNull String tag) { getSupportFragmentManager() .beginTransaction() .add(getContainerViewId(), frag, tag) .commitAllowingStateLoss(); } /** * * @return 存放fragment的container 的ID */ protected @IdRes int getContainerViewId() { return R.id.container; } protected final <T extends View> T find(@IdRes int id) { return (T) findViewById(id); } public AppComponent getAppComponent() {
return ((App)getApplication()).getAppComponent();
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/module/gank/MeiziFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import java.util.ArrayList; import java.util.List; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * Created by 程序亦非猿 on 16/7/28. */ public class MeiziFragment extends RefreshFragment<GankMeiziAdapter> { public static final String TAG = "MeiziFragment"; private GankMeiziAdapter mAdapter;
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // Path: app/src/main/java/me/yifeiyuan/climb/module/gank/MeiziFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import java.util.ArrayList; import java.util.List; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * Created by 程序亦非猿 on 16/7/28. */ public class MeiziFragment extends RefreshFragment<GankMeiziAdapter> { public static final String TAG = "MeiziFragment"; private GankMeiziAdapter mAdapter;
private ArrayList<GankEntity> mDatas;
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/module/gank/IosFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // }
import android.os.Bundle; import java.util.ArrayList; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * * gank.io iOS 内容 * */ public class IosFragment extends RefreshFragment<GankAdapter> { private GankAdapter mAdapter;
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // Path: app/src/main/java/me/yifeiyuan/climb/module/gank/IosFragment.java import android.os.Bundle; import java.util.ArrayList; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * * gank.io iOS 内容 * */ public class IosFragment extends RefreshFragment<GankAdapter> { private GankAdapter mAdapter;
private ArrayList<GankEntity> mDatas;
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/ToolbarFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/module/main/OpenDrawerEvent.java // public class OpenDrawerEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // }
import android.support.annotation.MenuRes; import android.support.v7.widget.Toolbar; import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.main.OpenDrawerEvent; import me.yifeiyuan.climb.tools.bus.OldDriver;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/9/29. * * 脱离 ActionBar 单纯使用 Toolbar */ public abstract class ToolbarFragment extends BaseFragment implements Toolbar.OnMenuItemClickListener { // 不能为 null @Bind(R.id.toolbar) protected Toolbar mToolbar; /** * @param title 标题 * @param menu 菜单 */ public void setupToolbar(String title, @MenuRes int menu) { mToolbar.setTitle(title); mToolbar.inflateMenu(menu); mToolbar.setOnMenuItemClickListener(this); mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_white)); mToolbar.setNavigationOnClickListener(v -> {
// Path: app/src/main/java/me/yifeiyuan/climb/module/main/OpenDrawerEvent.java // public class OpenDrawerEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/ToolbarFragment.java import android.support.annotation.MenuRes; import android.support.v7.widget.Toolbar; import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.main.OpenDrawerEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/9/29. * * 脱离 ActionBar 单纯使用 Toolbar */ public abstract class ToolbarFragment extends BaseFragment implements Toolbar.OnMenuItemClickListener { // 不能为 null @Bind(R.id.toolbar) protected Toolbar mToolbar; /** * @param title 标题 * @param menu 菜单 */ public void setupToolbar(String title, @MenuRes int menu) { mToolbar.setTitle(title); mToolbar.inflateMenu(menu); mToolbar.setOnMenuItemClickListener(this); mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_white)); mToolbar.setNavigationOnClickListener(v -> {
OldDriver.getIns().post(new OpenDrawerEvent());
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/ToolbarFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/module/main/OpenDrawerEvent.java // public class OpenDrawerEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // }
import android.support.annotation.MenuRes; import android.support.v7.widget.Toolbar; import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.main.OpenDrawerEvent; import me.yifeiyuan.climb.tools.bus.OldDriver;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/9/29. * * 脱离 ActionBar 单纯使用 Toolbar */ public abstract class ToolbarFragment extends BaseFragment implements Toolbar.OnMenuItemClickListener { // 不能为 null @Bind(R.id.toolbar) protected Toolbar mToolbar; /** * @param title 标题 * @param menu 菜单 */ public void setupToolbar(String title, @MenuRes int menu) { mToolbar.setTitle(title); mToolbar.inflateMenu(menu); mToolbar.setOnMenuItemClickListener(this); mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_white)); mToolbar.setNavigationOnClickListener(v -> {
// Path: app/src/main/java/me/yifeiyuan/climb/module/main/OpenDrawerEvent.java // public class OpenDrawerEvent { // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/bus/OldDriver.java // public class OldDriver implements IBus { // // private static OldDriver sIns = new OldDriver(); // // private EventBus mBus = new EventBus(); // // public static OldDriver getIns() { // return sIns; // } // // @Override // public void post(Object event) { // mBus.post(event); // } // // @Override // public void register(Object o) { // mBus.register(o); // } // // @Override // public void unregister(Object o) { // mBus.unregister(o); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/ToolbarFragment.java import android.support.annotation.MenuRes; import android.support.v7.widget.Toolbar; import butterknife.Bind; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.module.main.OpenDrawerEvent; import me.yifeiyuan.climb.tools.bus.OldDriver; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/9/29. * * 脱离 ActionBar 单纯使用 Toolbar */ public abstract class ToolbarFragment extends BaseFragment implements Toolbar.OnMenuItemClickListener { // 不能为 null @Bind(R.id.toolbar) protected Toolbar mToolbar; /** * @param title 标题 * @param menu 菜单 */ public void setupToolbar(String title, @MenuRes int menu) { mToolbar.setTitle(title); mToolbar.inflateMenu(menu); mToolbar.setOnMenuItemClickListener(this); mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_white)); mToolbar.setNavigationOnClickListener(v -> {
OldDriver.getIns().post(new OpenDrawerEvent());
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/ui/view/OpOnScrollListener.java
// Path: app/src/main/java/me/yifeiyuan/climb/tools/Checker.java // public static <T> T nonNull(T t) { // if (t == null) { // throw new NullPointerException(""); // } // return t; // }
import android.support.v7.widget.RecyclerView; import static me.yifeiyuan.climb.tools.Checker.nonNull;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.ui.view; /** * Created by 程序亦非猿 on 16/7/28. */ public class OpOnScrollListener extends RecyclerView.OnScrollListener { private boolean isLoading; private BottomDetector mBottomDetector; public OpOnScrollListener(RecyclerView.LayoutManager lm, OnBottomListener listener) { mBottomDetector = BottomDetectorFactory.create(lm);
// Path: app/src/main/java/me/yifeiyuan/climb/tools/Checker.java // public static <T> T nonNull(T t) { // if (t == null) { // throw new NullPointerException(""); // } // return t; // } // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/OpOnScrollListener.java import android.support.v7.widget.RecyclerView; import static me.yifeiyuan.climb.tools.Checker.nonNull; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.ui.view; /** * Created by 程序亦非猿 on 16/7/28. */ public class OpOnScrollListener extends RecyclerView.OnScrollListener { private boolean isLoading; private BottomDetector mBottomDetector; public OpOnScrollListener(RecyclerView.LayoutManager lm, OnBottomListener listener) { mBottomDetector = BottomDetectorFactory.create(lm);
mOnBottomListener = nonNull(listener);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // }
import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable;
package me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/6/1 下午5:29. * Climb * * https://github.com/izzyleung/ZhihuDailyPurify/wiki/%E7%9F%A5%E4%B9%8E%E6%97%A5%E6%8A%A5-API-%E5%88%86%E6%9E%90 */ public interface ZhiHuApi { @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776")
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // } // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable; package me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/6/1 下午5:29. * Climb * * https://github.com/izzyleung/ZhihuDailyPurify/wiki/%E7%9F%A5%E4%B9%8E%E6%97%A5%E6%8A%A5-API-%E5%88%86%E6%9E%90 */ public interface ZhiHuApi { @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776")
Observable<SplashEntity> getWel();
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/base/CxtSubscriber.java
// Path: app/src/main/java/me/yifeiyuan/climb/ui/widget/ToastUtil.java // public class ToastUtil { // // private static Toast sToast ; // // public static void show(@NonNull Context cxt,@NonNull CharSequence content) { // if (null == sToast) { // sToast = Toast.makeText(cxt.getApplicationContext(), content, Toast.LENGTH_SHORT); // } // sToast.setText(content); // sToast.show(); // } // }
import android.content.Context; import me.yifeiyuan.climb.ui.widget.ToastUtil;
/* * Copyright (C) 2015, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/7/14. */ public class CxtSubscriber<T> extends BaseSubscriber<T>{ protected Context mContext; public CxtSubscriber(Context cxt) { mContext = cxt; } @Override public void onError(Throwable e) {
// Path: app/src/main/java/me/yifeiyuan/climb/ui/widget/ToastUtil.java // public class ToastUtil { // // private static Toast sToast ; // // public static void show(@NonNull Context cxt,@NonNull CharSequence content) { // if (null == sToast) { // sToast = Toast.makeText(cxt.getApplicationContext(), content, Toast.LENGTH_SHORT); // } // sToast.setText(content); // sToast.show(); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/base/CxtSubscriber.java import android.content.Context; import me.yifeiyuan.climb.ui.widget.ToastUtil; /* * Copyright (C) 2015, 程序亦非猿 * * 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 me.yifeiyuan.climb.base; /** * Created by 程序亦非猿 on 16/7/14. */ public class CxtSubscriber<T> extends BaseSubscriber<T>{ protected Context mContext; public CxtSubscriber(Context cxt) { mContext = cxt; } @Override public void onError(Throwable e) {
ToastUtil.show(mContext,e.getMessage());
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/module/gank/AndFragment.java
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // }
import android.support.v4.app.Fragment; import java.util.ArrayList; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription;
/* * Copyright (C) 2015, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * A simple {@link Fragment} subclass. * Use the {@link AndFragment#newInstance} factory method to * create an instance of this fragment. */ public class AndFragment extends RefreshFragment<GankAdapter> { public static final String TAG = "AndFragment"; private GankAdapter mAdapter;
// Path: app/src/main/java/me/yifeiyuan/climb/base/RefreshFragment.java // public abstract class RefreshFragment<A extends RecyclerView.Adapter> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OpRecyclerView.OnLoadMoreListener { // // @Bind(R.id.rv) // protected OpRecyclerView mRecyclerView; // // @Bind(R.id.refresh) // protected SwipeRefreshLayout mSwipeRefreshLayout; // // @Nullable // @Bind(R.id.fab) // protected FloatingActionButton mFab; // // @Nullable // @Bind(R.id.col) // protected CoordinatorLayout mCol; // // /** // * 页码 // */ // protected int mCurrPage = 1; // // // @Override // protected int getLayoutId() { // return R.layout.base_refresh_fragment; // } // // /** // * 处理公用的view的初始化 // * // * @param savedInstanceState // */ // @CallSuper // @Override // protected void initView(@Nullable Bundle savedInstanceState) { // // OldDriver.getIns().register(this); // mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // mSwipeRefreshLayout.setOnRefreshListener(this); // mRecyclerView.setOnLoadMoreListener(this); // mRecyclerView.setLayoutManager(getLayoutManager()); // mRecyclerView.setAdapter(getAdapter()); // } // // @Override // public void onRefresh() { // requestData(true, true); // } // // @Override // public void onLoadMore() { // requestData(false, false); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // OldDriver.getIns().unregister(this); // } // // protected void setRefreshing(boolean refreshing) { // mSwipeRefreshLayout.setRefreshing(refreshing); // } // // protected void setLoadMoreComplete() { // mRecyclerView.setLoadMoreComplete(); // } // // protected abstract A getAdapter(); // // protected RecyclerView.LayoutManager getLayoutManager() { // if (mRecyclerView.getLayoutManager() != null) { // return mRecyclerView.getLayoutManager(); // } // return new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false); // } // // @Override // protected void requestData(boolean isForce, boolean isRefresh) { // if (isRefresh) { // mCurrPage = 1; // setRefreshing(true); // } else { // mCurrPage++; // } // Log.d(TAG, "TAG" + TAG + "requestData() called with: " + "isForce = [" + isForce + "], isRefresh = [" + isRefresh + "]"); // addSubscription(onRequestData(isForce, isRefresh)); // } // // abstract protected Subscription onRequestData(boolean isForce, boolean isRefresh); // // /** // * 默认处理处理 // * // * @param <T> // */ // protected class RefreshSubscriber<T> extends Subscriber<T> { // // /** 是否强制刷新 */ // boolean isForce; // /** 是否是刷新 */ // boolean isRefresh; // // protected RefreshSubscriber(boolean isForce, boolean isRefresh) { // this.isForce = isForce; // this.isRefresh = isRefresh; // } // // @Override // public void onCompleted() { // setRefreshing(false); // } // // @Override // public void onError(Throwable e) { // setRefreshing(false); // if (mCurrPage != 1) { // setLoadMoreComplete(); // } // Snackbar snackbar = Snackbar.make(mRootView, "ooops 出错啦!", Snackbar.LENGTH_LONG); // snackbar.setAction("重试", v -> { // mCurrPage--; // requestData(isForce, isRefresh); // }); // snackbar.show(); // } // // @Override // public void onNext(T t) { // // } // } // // @Subscribe // public void onReturnTop(ReturnTopEvent event) { // if (getUserVisibleHint() && getLayoutManager() instanceof LinearLayoutManager) { // ((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(0, 0); // } // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // Path: app/src/main/java/me/yifeiyuan/climb/module/gank/AndFragment.java import android.support.v4.app.Fragment; import java.util.ArrayList; import me.yifeiyuan.climb.base.RefreshFragment; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.entity.GankEntity; import rx.Subscription; /* * Copyright (C) 2015, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * A simple {@link Fragment} subclass. * Use the {@link AndFragment#newInstance} factory method to * create an instance of this fragment. */ public class AndFragment extends RefreshFragment<GankAdapter> { public static final String TAG = "AndFragment"; private GankAdapter mAdapter;
private ArrayList<GankEntity> mDatas;
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // }
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.modules; /** * Created by 程序亦非猿 on 16/10/18. */ @Module public class ApiModule { @Singleton @Provides OkHttpClient provideOkHttpClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(30_000, TimeUnit.MILLISECONDS) .readTimeout(30_000, TimeUnit.MILLISECONDS) .writeTimeout(30_000, TimeUnit.MILLISECONDS); if (BuildConfig.DEBUG) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(logging); } return builder.build(); } @Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder()
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // } // Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.modules; /** * Created by 程序亦非猿 on 16/10/18. */ @Module public class ApiModule { @Singleton @Provides OkHttpClient provideOkHttpClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(30_000, TimeUnit.MILLISECONDS) .readTimeout(30_000, TimeUnit.MILLISECONDS) .writeTimeout(30_000, TimeUnit.MILLISECONDS); if (BuildConfig.DEBUG) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(logging); } return builder.build(); } @Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GankConfig.URL_DOMAIN)
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // }
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi;
logging.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(logging); } return builder.build(); } @Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // } // Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi; logging.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(logging); } return builder.build(); } @Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides
GankApi provideGankApi(Retrofit retrofit) {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // }
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi;
@Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides GankApi provideGankApi(Retrofit retrofit) { return retrofit.create(GankApi.class); } @Singleton @Provides
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // } // Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi; @Singleton @Provides Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides GankApi provideGankApi(Retrofit retrofit) { return retrofit.create(GankApi.class); } @Singleton @Provides
ZhiHuApi provideZhiHuApi(Retrofit retrofit) {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // }
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi;
.create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides GankApi provideGankApi(Retrofit retrofit) { return retrofit.create(GankApi.class); } @Singleton @Provides ZhiHuApi provideZhiHuApi(Retrofit retrofit) { return retrofit.create(ZhiHuApi.class); } @Singleton @Provides
// Path: app/src/main/java/me/yifeiyuan/climb/data/GankConfig.java // public class GankConfig { // // public static final String URL_DOMAIN = "http://gank.io/api/"; // // public static final String URL_DAILY = "http://gank.avosapps.com/api/day/"; // // public static final String URL_RANDOM = "http://gank.avosapps.com/api/random/data/Android/"; // // public static final String ANDROID = "Android"; // // public static final int PAGE_COUNT = 30; // public static final int MEIZI_COUNT = 20; // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/GankApi.java // public interface GankApi { // // @GET("data/Android/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAndroid(@Path("page") int page); // // @GET("data/iOS/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getIos(@Path("page") int page); // // @GET("data/all/"+ GankConfig.PAGE_COUNT+"/{page}") // Observable<GankResponse> getAll(@Path("page") int page); // // // http://gank.avosapps.com/api/day/2015/08/06 // @GET("day/{year}/{month}/{day}") // Observable<GankDaily> getDaily(@Path("year") int year, @Path("month") int month, @Path("day") int day); // // @GET("data/福利/"+GankConfig.MEIZI_COUNT+"/{page}") // Observable<GankResponse> getMeizi(@Path("page") int page); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/WeatherApi.java // public interface WeatherApi { // // // https://api.heweather.com/x3/weather?cityid=城市ID&key=你的认证key // // @GET("https://api.heweather.com/x3/weather?") // // Observable<RequestBody> getWeather(@Query("cityid") String city, @Query("key")String key); // // @GET("http://apis.baidu.com/heweather/weather/free") // @Headers({"apikey:"+ Config.BAIDU_WEATHER}) // Observable<RequestBody> getWeather(@Query("city") String city); // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/ZhiHuApi.java // public interface ZhiHuApi { // // // @GET("http://news-at.zhihu.com/api/4/start-image/1080*1776") // Observable<SplashEntity> getWel(); // // // /**主题日报列表*/ // @GET("http://news-at.zhihu.com/api/4/themes") // Observable<RequestBody> themeList(); // // /**主题日报内容*/ // @GET("http://news-at.zhihu.com/api/4/theme/{themeId}") // Observable<RequestBody> themeDetails(@Path("themeId") int themeId); // } // Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.yifeiyuan.climb.BuildConfig; import me.yifeiyuan.climb.data.GankConfig; import me.yifeiyuan.climb.network.api.GankApi; import me.yifeiyuan.climb.network.api.WeatherApi; import me.yifeiyuan.climb.network.api.ZhiHuApi; .create(); } @Singleton @Provides Retrofit provideRetrofit(OkHttpClient client, Gson gson) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(GankConfig.URL_DOMAIN) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .client(client) .build(); return retrofit; } @Singleton @Provides GankApi provideGankApi(Retrofit retrofit) { return retrofit.create(GankApi.class); } @Singleton @Provides ZhiHuApi provideZhiHuApi(Retrofit retrofit) { return retrofit.create(ZhiHuApi.class); } @Singleton @Provides
WeatherApi provideWeatherApi(Retrofit retrofit) {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/ui/view/BottomDetectorFactory.java
// Path: app/src/main/java/me/yifeiyuan/climb/tools/Checker.java // public class Checker { // // public static <T> T nonNull(T t) { // if (t == null) { // throw new NullPointerException(""); // } // return t; // } // }
import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import me.yifeiyuan.climb.tools.Checker;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.ui.view; /** * Created by 程序亦非猿 on 16/7/28. */ public class BottomDetectorFactory { public static BottomDetector create(@NonNull RecyclerView.LayoutManager lm) {
// Path: app/src/main/java/me/yifeiyuan/climb/tools/Checker.java // public class Checker { // // public static <T> T nonNull(T t) { // if (t == null) { // throw new NullPointerException(""); // } // return t; // } // } // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/BottomDetectorFactory.java import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import me.yifeiyuan.climb.tools.Checker; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.ui.view; /** * Created by 程序亦非猿 on 16/7/28. */ public class BottomDetectorFactory { public static BottomDetector create(@NonNull RecyclerView.LayoutManager lm) {
Checker.nonNull(lm);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/app/AppStatusManager.java
// Path: app/src/main/java/me/yifeiyuan/climb/tools/trace/Agent.java // public class Agent { // // public static void onEvent(Context context, String eventName, String s1) { // if (enable()) { // MobclickAgent.onEvent(context, eventName, s1); // } // } // // public static void onEvent(Context context, String eventName) { // if (enable()) { // MobclickAgent.onEvent(context, eventName); // } // } // // // public static void onResume(Context context) { // if (enable()) { // MobclickAgent.onResume(context); // } // } // // public static void onPause(Context context) { // if (enable()) { // MobclickAgent.onPause(context); // } // } // // public static void onPageStart(String s) { // if (enable()) { // MobclickAgent.onPageStart(s); // } // } // // public static void onPageEnd(String s) { // if (enable()) { // MobclickAgent.onPageEnd(s); // } // } // // private static boolean enable() { // // 控制开关 // // return !BuildConfig.DEBUG; // return true; // } // }
import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.util.Log; import me.yifeiyuan.climb.tools.trace.Agent;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.app; /** * Created by 程序亦非猿 on 16/12/20. */ public class AppStatusManager implements Application.ActivityLifecycleCallbacks { private static final String TAG = "AppStatusManager"; private int activityCount; /** * 是否在前台 */ private boolean isForeground; private AppStatusManager() { } public void init(Application app) { app.registerActivityLifecycleCallbacks(this); } private static class Holder { private static final AppStatusManager INSTANCE = new AppStatusManager(); } public static AppStatusManager getInstance() { return Holder.INSTANCE; } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { activityCount++; isForeground = true; } @Override public void onActivityResumed(Activity activity) {
// Path: app/src/main/java/me/yifeiyuan/climb/tools/trace/Agent.java // public class Agent { // // public static void onEvent(Context context, String eventName, String s1) { // if (enable()) { // MobclickAgent.onEvent(context, eventName, s1); // } // } // // public static void onEvent(Context context, String eventName) { // if (enable()) { // MobclickAgent.onEvent(context, eventName); // } // } // // // public static void onResume(Context context) { // if (enable()) { // MobclickAgent.onResume(context); // } // } // // public static void onPause(Context context) { // if (enable()) { // MobclickAgent.onPause(context); // } // } // // public static void onPageStart(String s) { // if (enable()) { // MobclickAgent.onPageStart(s); // } // } // // public static void onPageEnd(String s) { // if (enable()) { // MobclickAgent.onPageEnd(s); // } // } // // private static boolean enable() { // // 控制开关 // // return !BuildConfig.DEBUG; // return true; // } // } // Path: app/src/main/java/me/yifeiyuan/climb/app/AppStatusManager.java import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.util.Log; import me.yifeiyuan.climb.tools.trace.Agent; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.app; /** * Created by 程序亦非猿 on 16/12/20. */ public class AppStatusManager implements Application.ActivityLifecycleCallbacks { private static final String TAG = "AppStatusManager"; private int activityCount; /** * 是否在前台 */ private boolean isForeground; private AppStatusManager() { } public void init(Application app) { app.registerActivityLifecycleCallbacks(this); } private static class Holder { private static final AppStatusManager INSTANCE = new AppStatusManager(); } public static AppStatusManager getInstance() { return Holder.INSTANCE; } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { activityCount++; isForeground = true; } @Override public void onActivityResumed(Activity activity) {
Agent.onResume(activity);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/module/gank/GankMeiziAdapter.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/Navigator.java // public class Navigator { // // // public static void go2PhotoActivity(Context cxt, String url){ // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("climb://photo/url=" + url)); // cxt.startActivity(intent); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/RatioImageView.java // public class RatioImageView extends ImageView { // // private float mRatio = 1.0f; // // public RatioImageView(Context context) { // this(context,null,0); // } // // public RatioImageView(Context context, AttributeSet attrs) { // this(context, attrs,0); // } // // public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView); // if (null != ta) { // mRatio = ta.getFloat(R.styleable.RatioImageView_ratio, 1.0f); // } // ta.recycle(); // } // // public float getRatio() { // return mRatio; // } // // public void setRatio(float ratio) { // mRatio = ratio; // } // // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int width = getMeasuredWidth(); // int height = (int) (width*mRatio); // setMeasuredDimension(width, height); // } // }
import me.yifeiyuan.climb.tools.Navigator; import me.yifeiyuan.climb.ui.view.RatioImageView; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.data.entity.GankEntity;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * Created by 程序亦非猿 on 16/7/28. */ public class GankMeiziAdapter extends RecyclerView.Adapter<GankMeiziAdapter.GankViewHolder>{ private List<GankEntity> mDatas; private Context mContext; public GankMeiziAdapter(Context context, List<GankEntity> mDatas) { this.mContext = context; this.mDatas = mDatas; } @Override public GankViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.gank_item_meizi, parent, false); return new GankViewHolder(view); } @Override public void onBindViewHolder(final GankViewHolder holder, int position) { final GankEntity entity = mDatas.get(position); Glide.with(mContext) .load(entity.url) // .placeholder(R.mipmap.ic_launcher) // .error(R.mipmap.ic_launcher) // .override(300,400) // .crossFade(R.anim.fade_in) .centerCrop() .into(holder.ivMeizi); holder.itemView.setOnClickListener(v -> {
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/Navigator.java // public class Navigator { // // // public static void go2PhotoActivity(Context cxt, String url){ // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("climb://photo/url=" + url)); // cxt.startActivity(intent); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/RatioImageView.java // public class RatioImageView extends ImageView { // // private float mRatio = 1.0f; // // public RatioImageView(Context context) { // this(context,null,0); // } // // public RatioImageView(Context context, AttributeSet attrs) { // this(context, attrs,0); // } // // public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView); // if (null != ta) { // mRatio = ta.getFloat(R.styleable.RatioImageView_ratio, 1.0f); // } // ta.recycle(); // } // // public float getRatio() { // return mRatio; // } // // public void setRatio(float ratio) { // mRatio = ratio; // } // // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int width = getMeasuredWidth(); // int height = (int) (width*mRatio); // setMeasuredDimension(width, height); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/module/gank/GankMeiziAdapter.java import me.yifeiyuan.climb.tools.Navigator; import me.yifeiyuan.climb.ui.view.RatioImageView; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.data.entity.GankEntity; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.module.gank; /** * Created by 程序亦非猿 on 16/7/28. */ public class GankMeiziAdapter extends RecyclerView.Adapter<GankMeiziAdapter.GankViewHolder>{ private List<GankEntity> mDatas; private Context mContext; public GankMeiziAdapter(Context context, List<GankEntity> mDatas) { this.mContext = context; this.mDatas = mDatas; } @Override public GankViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.gank_item_meizi, parent, false); return new GankViewHolder(view); } @Override public void onBindViewHolder(final GankViewHolder holder, int position) { final GankEntity entity = mDatas.get(position); Glide.with(mContext) .load(entity.url) // .placeholder(R.mipmap.ic_launcher) // .error(R.mipmap.ic_launcher) // .override(300,400) // .crossFade(R.anim.fade_in) .centerCrop() .into(holder.ivMeizi); holder.itemView.setOnClickListener(v -> {
Navigator.go2PhotoActivity(mContext,entity.url);
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/module/gank/GankMeiziAdapter.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/Navigator.java // public class Navigator { // // // public static void go2PhotoActivity(Context cxt, String url){ // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("climb://photo/url=" + url)); // cxt.startActivity(intent); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/RatioImageView.java // public class RatioImageView extends ImageView { // // private float mRatio = 1.0f; // // public RatioImageView(Context context) { // this(context,null,0); // } // // public RatioImageView(Context context, AttributeSet attrs) { // this(context, attrs,0); // } // // public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView); // if (null != ta) { // mRatio = ta.getFloat(R.styleable.RatioImageView_ratio, 1.0f); // } // ta.recycle(); // } // // public float getRatio() { // return mRatio; // } // // public void setRatio(float ratio) { // mRatio = ratio; // } // // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int width = getMeasuredWidth(); // int height = (int) (width*mRatio); // setMeasuredDimension(width, height); // } // }
import me.yifeiyuan.climb.tools.Navigator; import me.yifeiyuan.climb.ui.view.RatioImageView; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.data.entity.GankEntity;
@Override public void onBindViewHolder(final GankViewHolder holder, int position) { final GankEntity entity = mDatas.get(position); Glide.with(mContext) .load(entity.url) // .placeholder(R.mipmap.ic_launcher) // .error(R.mipmap.ic_launcher) // .override(300,400) // .crossFade(R.anim.fade_in) .centerCrop() .into(holder.ivMeizi); holder.itemView.setOnClickListener(v -> { Navigator.go2PhotoActivity(mContext,entity.url); if (null != mOnItemClickListener) { mOnItemClickListener.onItemClick(holder,entity); } }); } @Override public int getItemCount() { return mDatas.size(); } public class GankViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.iv_meizi)
// Path: app/src/main/java/me/yifeiyuan/climb/data/entity/GankEntity.java // public class GankEntity { // public String _id; // public String createdAt; // public String desc; // public String publishedAt; // public String source; // public String type; // public String url; // public boolean used; // public String who; // } // // Path: app/src/main/java/me/yifeiyuan/climb/tools/Navigator.java // public class Navigator { // // // public static void go2PhotoActivity(Context cxt, String url){ // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("climb://photo/url=" + url)); // cxt.startActivity(intent); // } // } // // Path: app/src/main/java/me/yifeiyuan/climb/ui/view/RatioImageView.java // public class RatioImageView extends ImageView { // // private float mRatio = 1.0f; // // public RatioImageView(Context context) { // this(context,null,0); // } // // public RatioImageView(Context context, AttributeSet attrs) { // this(context, attrs,0); // } // // public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView); // if (null != ta) { // mRatio = ta.getFloat(R.styleable.RatioImageView_ratio, 1.0f); // } // ta.recycle(); // } // // public float getRatio() { // return mRatio; // } // // public void setRatio(float ratio) { // mRatio = ratio; // } // // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int width = getMeasuredWidth(); // int height = (int) (width*mRatio); // setMeasuredDimension(width, height); // } // } // Path: app/src/main/java/me/yifeiyuan/climb/module/gank/GankMeiziAdapter.java import me.yifeiyuan.climb.tools.Navigator; import me.yifeiyuan.climb.ui.view.RatioImageView; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import me.yifeiyuan.climb.R; import me.yifeiyuan.climb.data.entity.GankEntity; @Override public void onBindViewHolder(final GankViewHolder holder, int position) { final GankEntity entity = mDatas.get(position); Glide.with(mContext) .load(entity.url) // .placeholder(R.mipmap.ic_launcher) // .error(R.mipmap.ic_launcher) // .override(300,400) // .crossFade(R.anim.fade_in) .centerCrop() .into(holder.ivMeizi); holder.itemView.setOnClickListener(v -> { Navigator.go2PhotoActivity(mContext,entity.url); if (null != mOnItemClickListener) { mOnItemClickListener.onItemClick(holder,entity); } }); } @Override public int getItemCount() { return mDatas.size(); } public class GankViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.iv_meizi)
RatioImageView ivMeizi;
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/di/components/ApiComponent.java
// Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java // @Module // public class ApiModule { // // @Singleton // @Provides // OkHttpClient provideOkHttpClient() { // OkHttpClient.Builder builder = new OkHttpClient.Builder() // .connectTimeout(30_000, TimeUnit.MILLISECONDS) // .readTimeout(30_000, TimeUnit.MILLISECONDS) // .writeTimeout(30_000, TimeUnit.MILLISECONDS); // // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addInterceptor(logging); // } // // return builder.build(); // } // // @Singleton // @Provides // Gson provideGson() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") // .create(); // } // // @Singleton // @Provides // Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // Retrofit retrofit = new Retrofit.Builder() // .baseUrl(GankConfig.URL_DOMAIN) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) // .client(client) // .build(); // // return retrofit; // } // // @Singleton // @Provides // GankApi provideGankApi(Retrofit retrofit) { // return retrofit.create(GankApi.class); // } // // @Singleton // @Provides // ZhiHuApi provideZhiHuApi(Retrofit retrofit) { // return retrofit.create(ZhiHuApi.class); // } // // @Singleton // @Provides // WeatherApi provideWeatherApi(Retrofit retrofit) { // return retrofit.create(WeatherApi.class); // } // // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/Api.java // public class Api { // // private final GankApi mGankApi; // private final ZhiHuApi mZhiHuApi; // private final WeatherApi mWeatherApi; // // @Inject // protected Api(GankApi gankApi,ZhiHuApi zhiHuApi,WeatherApi weatherApi) { // mGankApi = gankApi; // mZhiHuApi = zhiHuApi; // mWeatherApi = weatherApi; // } // // // TODO: 16/7/29 compose // // public Observable<GankResponse> getAndroid(int page) { // return wrap(mGankApi.getAndroid(page)); // } // // public Observable<GankResponse> getIos(int page) { // return wrap(mGankApi.getIos(page)); // } // // // public Observable<List<GIosEntity>> getIos(int page) { // // return apply(mGankApi.getIos(page)); // // } // // public Observable<GankResponse> getMeizi(int page) { // return wrap(mGankApi.getMeizi(page)); // } // // public Observable<GankDaily> getDaily(int year, int month, int day) { // return mGankApi.getDaily(year, month, day); // } // // public Observable<SplashEntity> getWel() { // return wrap(mZhiHuApi.getWel()); // } // // // public Observable<RequestBody> getWeather(String city) { // return wrap(mWeatherApi.getWeather(city)); // } // // private <T> Observable<T> wrap(Observable<T> o) { // return o.timeout(10_000,TimeUnit.MILLISECONDS) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()); // } // // private <T> Observable<T> apply(Observable<RxResponse<T>> observable) { // return observable.timeout(10_000, TimeUnit.MILLISECONDS) // .flatMap(new PickResults<>()) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()); // } // // private class PickResults<T> implements Func1<RxResponse<T>, Observable<T>> { // // @Override // public Observable<T> call(RxResponse<T> tRxResponse) { // return Observable.just(tRxResponse.results); // } // } // }
import javax.inject.Singleton; import dagger.Component; import me.yifeiyuan.climb.di.modules.ApiModule; import me.yifeiyuan.climb.network.api.Api;
/* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.components; /** * Created by 程序亦非猿 on 16/10/18. */ @Singleton @Component(modules = {ApiModule.class}) public interface ApiComponent {
// Path: app/src/main/java/me/yifeiyuan/climb/di/modules/ApiModule.java // @Module // public class ApiModule { // // @Singleton // @Provides // OkHttpClient provideOkHttpClient() { // OkHttpClient.Builder builder = new OkHttpClient.Builder() // .connectTimeout(30_000, TimeUnit.MILLISECONDS) // .readTimeout(30_000, TimeUnit.MILLISECONDS) // .writeTimeout(30_000, TimeUnit.MILLISECONDS); // // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addInterceptor(logging); // } // // return builder.build(); // } // // @Singleton // @Provides // Gson provideGson() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd") //("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") // .create(); // } // // @Singleton // @Provides // Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // Retrofit retrofit = new Retrofit.Builder() // .baseUrl(GankConfig.URL_DOMAIN) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) // .client(client) // .build(); // // return retrofit; // } // // @Singleton // @Provides // GankApi provideGankApi(Retrofit retrofit) { // return retrofit.create(GankApi.class); // } // // @Singleton // @Provides // ZhiHuApi provideZhiHuApi(Retrofit retrofit) { // return retrofit.create(ZhiHuApi.class); // } // // @Singleton // @Provides // WeatherApi provideWeatherApi(Retrofit retrofit) { // return retrofit.create(WeatherApi.class); // } // // } // // Path: app/src/main/java/me/yifeiyuan/climb/network/api/Api.java // public class Api { // // private final GankApi mGankApi; // private final ZhiHuApi mZhiHuApi; // private final WeatherApi mWeatherApi; // // @Inject // protected Api(GankApi gankApi,ZhiHuApi zhiHuApi,WeatherApi weatherApi) { // mGankApi = gankApi; // mZhiHuApi = zhiHuApi; // mWeatherApi = weatherApi; // } // // // TODO: 16/7/29 compose // // public Observable<GankResponse> getAndroid(int page) { // return wrap(mGankApi.getAndroid(page)); // } // // public Observable<GankResponse> getIos(int page) { // return wrap(mGankApi.getIos(page)); // } // // // public Observable<List<GIosEntity>> getIos(int page) { // // return apply(mGankApi.getIos(page)); // // } // // public Observable<GankResponse> getMeizi(int page) { // return wrap(mGankApi.getMeizi(page)); // } // // public Observable<GankDaily> getDaily(int year, int month, int day) { // return mGankApi.getDaily(year, month, day); // } // // public Observable<SplashEntity> getWel() { // return wrap(mZhiHuApi.getWel()); // } // // // public Observable<RequestBody> getWeather(String city) { // return wrap(mWeatherApi.getWeather(city)); // } // // private <T> Observable<T> wrap(Observable<T> o) { // return o.timeout(10_000,TimeUnit.MILLISECONDS) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()); // } // // private <T> Observable<T> apply(Observable<RxResponse<T>> observable) { // return observable.timeout(10_000, TimeUnit.MILLISECONDS) // .flatMap(new PickResults<>()) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()); // } // // private class PickResults<T> implements Func1<RxResponse<T>, Observable<T>> { // // @Override // public Observable<T> call(RxResponse<T> tRxResponse) { // return Observable.just(tRxResponse.results); // } // } // } // Path: app/src/main/java/me/yifeiyuan/climb/di/components/ApiComponent.java import javax.inject.Singleton; import dagger.Component; import me.yifeiyuan.climb.di.modules.ApiModule; import me.yifeiyuan.climb.network.api.Api; /* * Copyright (C) 2016, 程序亦非猿 * * 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 me.yifeiyuan.climb.di.components; /** * Created by 程序亦非猿 on 16/10/18. */ @Singleton @Component(modules = {ApiModule.class}) public interface ApiComponent {
Api api();
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/network/api/Api.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/RxResponse.java // public class RxResponse<T> extends BaseResponse{ // public T results; // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // }
import java.util.concurrent.TimeUnit; import javax.inject.Inject; import me.yifeiyuan.climb.data.GankDaily; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.RxResponse; import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers;
package me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/7/1. */ public class Api { private final GankApi mGankApi; private final ZhiHuApi mZhiHuApi; private final WeatherApi mWeatherApi; @Inject protected Api(GankApi gankApi,ZhiHuApi zhiHuApi,WeatherApi weatherApi) { mGankApi = gankApi; mZhiHuApi = zhiHuApi; mWeatherApi = weatherApi; } // TODO: 16/7/29 compose public Observable<GankResponse> getAndroid(int page) { return wrap(mGankApi.getAndroid(page)); } public Observable<GankResponse> getIos(int page) { return wrap(mGankApi.getIos(page)); } // public Observable<List<GIosEntity>> getIos(int page) { // return apply(mGankApi.getIos(page)); // } public Observable<GankResponse> getMeizi(int page) { return wrap(mGankApi.getMeizi(page)); } public Observable<GankDaily> getDaily(int year, int month, int day) { return mGankApi.getDaily(year, month, day); }
// Path: app/src/main/java/me/yifeiyuan/climb/data/RxResponse.java // public class RxResponse<T> extends BaseResponse{ // public T results; // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // } // Path: app/src/main/java/me/yifeiyuan/climb/network/api/Api.java import java.util.concurrent.TimeUnit; import javax.inject.Inject; import me.yifeiyuan.climb.data.GankDaily; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.RxResponse; import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; package me.yifeiyuan.climb.network.api; /** * Created by 程序亦非猿 on 16/7/1. */ public class Api { private final GankApi mGankApi; private final ZhiHuApi mZhiHuApi; private final WeatherApi mWeatherApi; @Inject protected Api(GankApi gankApi,ZhiHuApi zhiHuApi,WeatherApi weatherApi) { mGankApi = gankApi; mZhiHuApi = zhiHuApi; mWeatherApi = weatherApi; } // TODO: 16/7/29 compose public Observable<GankResponse> getAndroid(int page) { return wrap(mGankApi.getAndroid(page)); } public Observable<GankResponse> getIos(int page) { return wrap(mGankApi.getIos(page)); } // public Observable<List<GIosEntity>> getIos(int page) { // return apply(mGankApi.getIos(page)); // } public Observable<GankResponse> getMeizi(int page) { return wrap(mGankApi.getMeizi(page)); } public Observable<GankDaily> getDaily(int year, int month, int day) { return mGankApi.getDaily(year, month, day); }
public Observable<SplashEntity> getWel() {
AlanCheen/Climb
app/src/main/java/me/yifeiyuan/climb/network/api/Api.java
// Path: app/src/main/java/me/yifeiyuan/climb/data/RxResponse.java // public class RxResponse<T> extends BaseResponse{ // public T results; // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // }
import java.util.concurrent.TimeUnit; import javax.inject.Inject; import me.yifeiyuan.climb.data.GankDaily; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.RxResponse; import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers;
return wrap(mGankApi.getIos(page)); } // public Observable<List<GIosEntity>> getIos(int page) { // return apply(mGankApi.getIos(page)); // } public Observable<GankResponse> getMeizi(int page) { return wrap(mGankApi.getMeizi(page)); } public Observable<GankDaily> getDaily(int year, int month, int day) { return mGankApi.getDaily(year, month, day); } public Observable<SplashEntity> getWel() { return wrap(mZhiHuApi.getWel()); } public Observable<RequestBody> getWeather(String city) { return wrap(mWeatherApi.getWeather(city)); } private <T> Observable<T> wrap(Observable<T> o) { return o.timeout(10_000,TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }
// Path: app/src/main/java/me/yifeiyuan/climb/data/RxResponse.java // public class RxResponse<T> extends BaseResponse{ // public T results; // } // // Path: app/src/main/java/me/yifeiyuan/climb/data/entity/SplashEntity.java // public class SplashEntity { // public String text; // public String img; // } // Path: app/src/main/java/me/yifeiyuan/climb/network/api/Api.java import java.util.concurrent.TimeUnit; import javax.inject.Inject; import me.yifeiyuan.climb.data.GankDaily; import me.yifeiyuan.climb.data.GankResponse; import me.yifeiyuan.climb.data.RxResponse; import me.yifeiyuan.climb.data.entity.SplashEntity; import okhttp3.RequestBody; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; return wrap(mGankApi.getIos(page)); } // public Observable<List<GIosEntity>> getIos(int page) { // return apply(mGankApi.getIos(page)); // } public Observable<GankResponse> getMeizi(int page) { return wrap(mGankApi.getMeizi(page)); } public Observable<GankDaily> getDaily(int year, int month, int day) { return mGankApi.getDaily(year, month, day); } public Observable<SplashEntity> getWel() { return wrap(mZhiHuApi.getWel()); } public Observable<RequestBody> getWeather(String city) { return wrap(mWeatherApi.getWeather(city)); } private <T> Observable<T> wrap(Observable<T> o) { return o.timeout(10_000,TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }
private <T> Observable<T> apply(Observable<RxResponse<T>> observable) {
johndavidbustard/RoughWorld
src/tools/existing_dataset_processing/ConceptNet.java
// Path: src/web/WebClient.java // public class WebClient // { // public String root = "http://localhost"; // public String rootSSL = "https://localhost"; // //the web requests to be processed by the client // ArrayList<ArrayList<String> > queue = new ArrayList<ArrayList<String> >(); // // public WebClient() // { // } // // public WebClient(String root) // { // this.root = root; // } // // public static void setupSSL() // { // // System.setProperty("javax.net.ssl.trustStore", f.getAbsolutePath()); // // keytool -import -alias gridserver -file gridserver.crt -storepass $PASS -keystore gridserver.keystore // // // // -Djavax.net.ssl.keyStoreType=pkcs12 // // -Djavax.net.ssl.trustStoreType=jks // // -Djavax.net.ssl.keyStore=clientcertificate.p12 // // -Djavax.net.ssl.trustStore=gridserver.keystore // // -Djavax.net.debug=ssl # very verbose debug // // -Djavax.net.ssl.keyStorePassword=$PASS // // -Djavax.net.ssl.trustStorePassword=$PASS // disableCertificateValidation(); // } // public static void disableCertificateValidation() // { // // Create a trust manager that does not validate certificate chains // TrustManager[] trustAllCerts = new TrustManager[] // { // new TrustAllManager() // }; // // // Ignore differences between given hostname and certificate hostname // HostnameVerifier hv = new TrustAllHostnameVerifier(); // // // Install the all-trusting trust manager // try // { // SSLContext sc = SSLContext.getInstance("SSL"); // sc.init(null, trustAllCerts, new SecureRandom()); // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // HttpsURLConnection.setDefaultHostnameVerifier(hv); // } catch (Exception e) {} // } // // public synchronized void getQueue(ArrayList<ArrayList<String> > q) // { // q.addAll(queue); // queue.clear(); // } // public synchronized void queue(ArrayList<String> e) // { // queue.add(e); // } // // public void post(String path,HashMap<String,String> parameters) // { // String paramstring = ""; // Iterator<Map.Entry<String, String> > it = parameters.entrySet().iterator(); // boolean first = true; // while (it.hasNext()) { // Map.Entry<String, String> pair = it.next(); // if(!first) // paramstring += "&"; // paramstring += WebSecurity.encodeUri(pair.getKey())+"="+WebSecurity.encodeUri(pair.getValue()); // first = false; // } // // new WebClientRequest(this,root+path,paramstring); // } // // public String objAsString(String p, Object o) // { // if(o instanceof String) // { // return (String)o; // } // return "null"; // } // // public void post(String path,String p0,Object o0,File f) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // new WebClientRequest(this,root+path,res,f); // } // // public void post(String path,String p0,Object o0) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // new WebClientRequest(this,root+path,res); // } // // public void post(String path,String p0,Object o0,String p1,Object o1,String p2,Object o2) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // res += "&"; // res += WebSecurity.encodeUri(p1)+"="+WebSecurity.encodeUri(objAsString(p1,o1)); // res += "&"; // res += WebSecurity.encodeUri(p2)+"="+WebSecurity.encodeUri(objAsString(p2,o2)); // new WebClientRequest(this,root+path,res); // } // // public void post(String path) // { // new WebClientRequest(this,root+path,""); // } // // public void postSSL(String path) // { // new WebClientRequest(this,rootSSL+path,"",true); // } // // }
import java.util.ArrayList; import web.WebClient;
package tools.existing_dataset_processing; public class ConceptNet { public static void main(String[] commandLineParameters) throws Exception { getRoomsHTML(); } public static void getRoomConcept(String concept) { //We want to process a concept net room concept and construct a folder in the Concepts folder } public static void getRoomsAPI() { //get all the concept net entries that isa room try {
// Path: src/web/WebClient.java // public class WebClient // { // public String root = "http://localhost"; // public String rootSSL = "https://localhost"; // //the web requests to be processed by the client // ArrayList<ArrayList<String> > queue = new ArrayList<ArrayList<String> >(); // // public WebClient() // { // } // // public WebClient(String root) // { // this.root = root; // } // // public static void setupSSL() // { // // System.setProperty("javax.net.ssl.trustStore", f.getAbsolutePath()); // // keytool -import -alias gridserver -file gridserver.crt -storepass $PASS -keystore gridserver.keystore // // // // -Djavax.net.ssl.keyStoreType=pkcs12 // // -Djavax.net.ssl.trustStoreType=jks // // -Djavax.net.ssl.keyStore=clientcertificate.p12 // // -Djavax.net.ssl.trustStore=gridserver.keystore // // -Djavax.net.debug=ssl # very verbose debug // // -Djavax.net.ssl.keyStorePassword=$PASS // // -Djavax.net.ssl.trustStorePassword=$PASS // disableCertificateValidation(); // } // public static void disableCertificateValidation() // { // // Create a trust manager that does not validate certificate chains // TrustManager[] trustAllCerts = new TrustManager[] // { // new TrustAllManager() // }; // // // Ignore differences between given hostname and certificate hostname // HostnameVerifier hv = new TrustAllHostnameVerifier(); // // // Install the all-trusting trust manager // try // { // SSLContext sc = SSLContext.getInstance("SSL"); // sc.init(null, trustAllCerts, new SecureRandom()); // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // HttpsURLConnection.setDefaultHostnameVerifier(hv); // } catch (Exception e) {} // } // // public synchronized void getQueue(ArrayList<ArrayList<String> > q) // { // q.addAll(queue); // queue.clear(); // } // public synchronized void queue(ArrayList<String> e) // { // queue.add(e); // } // // public void post(String path,HashMap<String,String> parameters) // { // String paramstring = ""; // Iterator<Map.Entry<String, String> > it = parameters.entrySet().iterator(); // boolean first = true; // while (it.hasNext()) { // Map.Entry<String, String> pair = it.next(); // if(!first) // paramstring += "&"; // paramstring += WebSecurity.encodeUri(pair.getKey())+"="+WebSecurity.encodeUri(pair.getValue()); // first = false; // } // // new WebClientRequest(this,root+path,paramstring); // } // // public String objAsString(String p, Object o) // { // if(o instanceof String) // { // return (String)o; // } // return "null"; // } // // public void post(String path,String p0,Object o0,File f) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // new WebClientRequest(this,root+path,res,f); // } // // public void post(String path,String p0,Object o0) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // new WebClientRequest(this,root+path,res); // } // // public void post(String path,String p0,Object o0,String p1,Object o1,String p2,Object o2) // { // String res = ""; // res += WebSecurity.encodeUri(p0)+"="+WebSecurity.encodeUri(objAsString(p0,o0)); // res += "&"; // res += WebSecurity.encodeUri(p1)+"="+WebSecurity.encodeUri(objAsString(p1,o1)); // res += "&"; // res += WebSecurity.encodeUri(p2)+"="+WebSecurity.encodeUri(objAsString(p2,o2)); // new WebClientRequest(this,root+path,res); // } // // public void post(String path) // { // new WebClientRequest(this,root+path,""); // } // // public void postSSL(String path) // { // new WebClientRequest(this,rootSSL+path,"",true); // } // // } // Path: src/tools/existing_dataset_processing/ConceptNet.java import java.util.ArrayList; import web.WebClient; package tools.existing_dataset_processing; public class ConceptNet { public static void main(String[] commandLineParameters) throws Exception { getRoomsHTML(); } public static void getRoomConcept(String concept) { //We want to process a concept net room concept and construct a folder in the Concepts folder } public static void getRoomsAPI() { //get all the concept net entries that isa room try {
WebClient checkIP = new WebClient("http://api.conceptnet.io/c/en/room/n?offset=0&limit=1000");
amouat/diffxml
src/test/org/diffxml/patchxml/DULPatchTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static junit.framework.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.patchxml; /** * Class to test applying DUL Patches. * * @author Adrian Mouat * */ public class DULPatchTest { /** * Simple insert operation. */ @Test public final void testSimpleInsert() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/patchxml/DULPatchTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static junit.framework.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.patchxml; /** * Class to test applying DUL Patches. * * @author Adrian Mouat * */ public class DULPatchTest { /** * Simple insert operation. */ @Test public final void testSimpleInsert() {
Document doc1 = TestDocHelper.createDocument("<a></a>");
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/NodePairsTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import org.w3c.dom.Node; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test the NodePairs datatype works correctly. * * @author Adrian Mouat * */ public class NodePairsTest { /** Test Doc 1. */ private static Document mTestDoc1; /** Test Doc 2. */ private static Document mTestDoc2; /** * Set up the test docs. */ @BeforeClass public static void setUpBeforeClass() { String docString = "<a><b/><c/><d/></a>";
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/NodePairsTest.java import org.w3c.dom.Node; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test the NodePairs datatype works correctly. * * @author Adrian Mouat * */ public class NodePairsTest { /** Test Doc 1. */ private static Document mTestDoc1; /** Test Doc 2. */ private static Document mTestDoc2; /** * Set up the test docs. */ @BeforeClass public static void setUpBeforeClass() { String docString = "<a><b/><c/><d/></a>";
mTestDoc1 = TestDocHelper.createDocument(docString);
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/MatchTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Ignore; import org.w3c.dom.Document; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Class to test matching algorithm. * * TODO: Add more tests for similar docs and other node types. * * @author Adrian Mouat * */ public class MatchTest { /** Test Doc 1a. */ private static Document mTestDoc1a; /** Test Doc 1b. */ private static Document mTestDoc1b; /** Test Doc 2a. */ private static Document mTestDoc2a; /** Test Doc 2b. */ private static Document mTestDoc2b; /** Test Doc 3a. */ private static Document mTestDoc3a; /** Test Doc 3b. */ private static Document mTestDoc3b; /** Test Doc 4a. */ private static Document mTestDoc4a; /** * Set up documents before test. */ @BeforeClass public static void setUpBeforeClass() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/MatchTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Ignore; import org.w3c.dom.Document; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Class to test matching algorithm. * * TODO: Add more tests for similar docs and other node types. * * @author Adrian Mouat * */ public class MatchTest { /** Test Doc 1a. */ private static Document mTestDoc1a; /** Test Doc 1b. */ private static Document mTestDoc1b; /** Test Doc 2a. */ private static Document mTestDoc2a; /** Test Doc 2b. */ private static Document mTestDoc2b; /** Test Doc 3a. */ private static Document mTestDoc3a; /** Test Doc 3b. */ private static Document mTestDoc3b; /** Test Doc 4a. */ private static Document mTestDoc4a; /** * Set up documents before test. */ @BeforeClass public static void setUpBeforeClass() {
mTestDoc1a = TestDocHelper.createDocument("<a><b><c/></b></a>");
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/NodeSequenceTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.List; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test for NodeSequence class. * * @author Adrian Mouat * */ public class NodeSequenceTest { /** * Test getting sequence with all members in common. */ @Test public final void testSequenceAllInCommon() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/NodeSequenceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.List; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test for NodeSequence class. * * @author Adrian Mouat * */ public class NodeSequenceTest { /** * Test getting sequence with all members in common. */ @Test public final void testSequenceAllInCommon() {
Document seq1 = TestDocHelper.createDocument(
amouat/diffxml
src/java/org/diffxml/diffxml/DiffFactory.java
// Path: src/java/org/diffxml/diffxml/fmes/Fmes.java // public class Fmes implements Diff { // // /** // * Determines if the given node should be ignored. // * // * Examines the node's type against settings. // * // * @return True if the node is banned, false otherwise // * @param n The node to be checked // */ // // public static boolean isBanned(final Node n) { // // boolean ret = false; // // Check if ignorable whitespace // if (DiffFactory.isIgnoreWhitespaceNodes() && DOMOps.isText(n)) { // StringTokenizer st = new StringTokenizer(n.getNodeValue()); // if (!st.hasMoreTokens()) { // ret = true; // } // } // // // Check if ignorable comment // if (DiffFactory.isIgnoreComments() // && (n.getNodeType() == Node.COMMENT_NODE)) { // ret = true; // } // // // Check if ignorable pi // if (DiffFactory.isIgnoreProcessingInstructions() // && (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)) { // ret = true; // } // // return ret; // } // // /** // * Calls fmes diff on two files. // * // * @return The delta // * @param file1 The original file // * @param file2 The modified file // * @throws DiffException If something goes wrong during the diff // **/ // public final Document diff(final File file1, final File file2) // throws DiffException { // // // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // DocumentBuilder db = null; // Document doc1 = null; // Document doc2 = null; // // try { // db = fac.newDocumentBuilder(); // doc1 = db.parse(file1); // } catch (ParserConfigurationException e) { // throw new DiffException("Failed to set up XML parser", e); // } catch (IOException e) { // throw new DiffException("Failed to parse file " // + file1.getAbsolutePath(), e); // } catch (SAXException e) { // throw new DiffException("Failed to parse file " // + file1.getAbsolutePath(), e); // } // // try { // doc2 = db.parse(file2); // } catch (IOException e) { // throw new DiffException("Failed to parse file " // + file2.getAbsolutePath(), e); // } catch (SAXException e) { // throw new DiffException("Failed to parse file " // + file2.getAbsolutePath(), e); // } // // return diff(doc1, doc2); // } // // /** // * Differences two DOM documents and returns the delta. // * // * The delta is in DUL format. // * // * @param doc1 The original document // * @param doc2 The new document // * // * @return A document describing the changes // * required to make doc1 into doc2. // * @throws DiffException If something goes wrong during the diff // */ // // public final Document diff(final Document doc1, final Document doc2) // throws DiffException { // // NodePairs matchings = Match.easyMatch(doc1, doc2); // // Document delta = null; // try { // delta = (new EditScript(doc1, doc2, matchings)).create(); // } catch (DocumentCreationException e) { // throw new DiffException("Failed to create Edit Script ", e); // } // // return delta; // } // }
import org.diffxml.diffxml.fmes.Fmes;
return mDUL; } /** * Sets whether external entities should be resolved. * * @param resolve If true, external entities are resolved. */ public static void setResolveEntities(final boolean resolve) { mResolveEntities = resolve; } /** * Gets whether external entities should be resolved. * * @return True if external entities are resolved. */ public static boolean isResolveEntities() { return mResolveEntities; } /** * Creates an instance of the appropriate Diff engine. * * Currently only FMES, may be more in future. * * @return a difference engine meeting implementing the Diff interface */ public static Diff createDiff() {
// Path: src/java/org/diffxml/diffxml/fmes/Fmes.java // public class Fmes implements Diff { // // /** // * Determines if the given node should be ignored. // * // * Examines the node's type against settings. // * // * @return True if the node is banned, false otherwise // * @param n The node to be checked // */ // // public static boolean isBanned(final Node n) { // // boolean ret = false; // // Check if ignorable whitespace // if (DiffFactory.isIgnoreWhitespaceNodes() && DOMOps.isText(n)) { // StringTokenizer st = new StringTokenizer(n.getNodeValue()); // if (!st.hasMoreTokens()) { // ret = true; // } // } // // // Check if ignorable comment // if (DiffFactory.isIgnoreComments() // && (n.getNodeType() == Node.COMMENT_NODE)) { // ret = true; // } // // // Check if ignorable pi // if (DiffFactory.isIgnoreProcessingInstructions() // && (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)) { // ret = true; // } // // return ret; // } // // /** // * Calls fmes diff on two files. // * // * @return The delta // * @param file1 The original file // * @param file2 The modified file // * @throws DiffException If something goes wrong during the diff // **/ // public final Document diff(final File file1, final File file2) // throws DiffException { // // // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // DocumentBuilder db = null; // Document doc1 = null; // Document doc2 = null; // // try { // db = fac.newDocumentBuilder(); // doc1 = db.parse(file1); // } catch (ParserConfigurationException e) { // throw new DiffException("Failed to set up XML parser", e); // } catch (IOException e) { // throw new DiffException("Failed to parse file " // + file1.getAbsolutePath(), e); // } catch (SAXException e) { // throw new DiffException("Failed to parse file " // + file1.getAbsolutePath(), e); // } // // try { // doc2 = db.parse(file2); // } catch (IOException e) { // throw new DiffException("Failed to parse file " // + file2.getAbsolutePath(), e); // } catch (SAXException e) { // throw new DiffException("Failed to parse file " // + file2.getAbsolutePath(), e); // } // // return diff(doc1, doc2); // } // // /** // * Differences two DOM documents and returns the delta. // * // * The delta is in DUL format. // * // * @param doc1 The original document // * @param doc2 The new document // * // * @return A document describing the changes // * required to make doc1 into doc2. // * @throws DiffException If something goes wrong during the diff // */ // // public final Document diff(final Document doc1, final Document doc2) // throws DiffException { // // NodePairs matchings = Match.easyMatch(doc1, doc2); // // Document delta = null; // try { // delta = (new EditScript(doc1, doc2, matchings)).create(); // } catch (DocumentCreationException e) { // throw new DiffException("Failed to create Edit Script ", e); // } // // return delta; // } // } // Path: src/java/org/diffxml/diffxml/DiffFactory.java import org.diffxml.diffxml.fmes.Fmes; return mDUL; } /** * Sets whether external entities should be resolved. * * @param resolve If true, external entities are resolved. */ public static void setResolveEntities(final boolean resolve) { mResolveEntities = resolve; } /** * Gets whether external entities should be resolved. * * @return True if external entities are resolved. */ public static boolean isResolveEntities() { return mResolveEntities; } /** * Creates an instance of the appropriate Diff engine. * * Currently only FMES, may be more in future. * * @return a difference engine meeting implementing the Diff interface */ public static Diff createDiff() {
return new Fmes();
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/EditScriptTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test main EditScript class and methods. * * TODO: Write helper method for these tests e.g. * checkOpIsInsert(3, b, /node()[1]) * * @author Adrian Mouat * */ public class EditScriptTest { /** * Test handling documents with different document elements. */ @Test public final void testNonMatchingDocumentElements() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/EditScriptTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test main EditScript class and methods. * * TODO: Write helper method for these tests e.g. * checkOpIsInsert(3, b, /node()[1]) * * @author Adrian Mouat * */ public class EditScriptTest { /** * Test handling documents with different document elements. */ @Test public final void testNonMatchingDocumentElements() {
Document doc1 = TestDocHelper.createDocument("<a><b/></a>");
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/NodeFifoTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test the NodeFifo works. * * Essentially a first-in-first-out form a stack with extra Node operations. * * @author Adrian Mouat * */ public class NodeFifoTest { /** * Test an empty fifo is empty. */ @Test public void testEmptyFifo() { NodeFifo fifo = new NodeFifo(); assertTrue(fifo.isEmpty()); assertNull(fifo.pop()); } /** * Test nodes are pushed and popped in the right order. */ @Test public final void testPushPopOrder() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/NodeFifoTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test the NodeFifo works. * * Essentially a first-in-first-out form a stack with extra Node operations. * * @author Adrian Mouat * */ public class NodeFifoTest { /** * Test an empty fifo is empty. */ @Test public void testEmptyFifo() { NodeFifo fifo = new NodeFifo(); assertTrue(fifo.isEmpty()); assertNull(fifo.pop()); } /** * Test nodes are pushed and popped in the right order. */ @Test public final void testPushPopOrder() {
Document testDoc = TestDocHelper.createDocument("<a><b><c/></b></a>");
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/FindPositionTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import static org.junit.Assert.assertEquals; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test FindPosition. * * @author Adrian Mouat */ public class FindPositionTest { /** * Test simple insert of element. */ @Test public final void testElementInsert() {
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/FindPositionTest.java import static org.junit.Assert.assertEquals; import org.diffxml.diffxml.TestDocHelper; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test FindPosition. * * @author Adrian Mouat */ public class FindPositionTest { /** * Test simple insert of element. */ @Test public final void testElementInsert() {
Document testDoc1 = TestDocHelper.createDocument("<a><b/></a>");
amouat/diffxml
src/test/org/diffxml/diffxml/fmes/NodeDepthTest.java
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // }
import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import static junit.framework.Assert.assertEquals; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node;
/* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test class for NodeDepth. * * @author Adrian Mouat * */ public class NodeDepthTest { /** Test document. */ private static Document mTestDoc1; /** * Initialises the test doc. */ @BeforeClass public static void setUpTest() { String docString = "<x>text1<y><!-- comment --><z/>text2</y></x>";
// Path: src/test/org/diffxml/diffxml/TestDocHelper.java // public final class TestDocHelper { // // /** // * Private constructor. // */ // private TestDocHelper() { // //SHouldn't be called // } // // /** // * Create an XML Document from a string of XML. // * // * Calls fail if any exception is thrown. // * // * @param xml The XML to turn into a document. // * @return A DOM document representing the string. // */ // public static Document createDocument(final String xml) { // // Document ret = null; // DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); // DOMOps.initParser(fac); // // try { // ByteArrayInputStream is = new ByteArrayInputStream( // xml.getBytes("utf-8")); // ret = fac.newDocumentBuilder().parse(is); // } catch (UnsupportedEncodingException e) { // fail("No utf-8 encoder!"); // } catch (ParserConfigurationException e) { // fail("Error configuring parser: " + e.getMessage()); // } catch (IOException e) { // fail("Caught IOException: " + e.getMessage()); // } catch (SAXException e) { // fail("Caught SAXexception: " + e.getMessage()); // } // // return ret; // // } // } // Path: src/test/org/diffxml/diffxml/fmes/NodeDepthTest.java import org.diffxml.diffxml.TestDocHelper; import org.junit.BeforeClass; import org.junit.Test; import static junit.framework.Assert.assertEquals; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /* diffxml and patchxml - diff and patch for XML files Copyright 2013 Adrian Mouat Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.diffxml.diffxml.fmes; /** * Test class for NodeDepth. * * @author Adrian Mouat * */ public class NodeDepthTest { /** Test document. */ private static Document mTestDoc1; /** * Initialises the test doc. */ @BeforeClass public static void setUpTest() { String docString = "<x>text1<y><!-- comment --><z/>text2</y></x>";
mTestDoc1 = TestDocHelper.createDocument(docString);
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/sketch/FrequencyCounts.java
// Path: src/main/java/edu/umd/marbl/mhap/impl/MhapRuntimeException.java // public class MhapRuntimeException extends RuntimeException // { // // /** // * // */ // private static final long serialVersionUID = 56387323839744808L; // // public MhapRuntimeException() // { // super(); // } // // public MhapRuntimeException(String message, Throwable cause) // { // super(message, cause); // } // // public MhapRuntimeException(String message) // { // super(message); // } // // public MhapRuntimeException(Throwable cause) // { // super(cause); // } // // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.google.common.hash.BloomFilter; import edu.umd.marbl.mhap.impl.MhapRuntimeException; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.io.BufferedReader; import java.io.IOException;
/* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.umd.marbl.mhap.sketch; public final class FrequencyCounts { private final double filterCutoff; private final Map<Long,Double> fractionCounts; private final Set<Integer> kmerSizes; private final double maxIdfValue; private final double maxValue; private final double minIdfValue; private final double minValue; private final boolean noTf; private final double offset; private final double range; private final int removeUnique; private final BloomFilter<Long> validMers; public FrequencyCounts(BufferedReader bf, double filterCutoff, double offset, int removeUnique, boolean noTf, int numThreads, double range, boolean doReverseCompliment) throws IOException { //removeUnique = 0: do nothing extra to k-mers not specified in the file //removeUnique = 1: remove k-mers not specified in the file from the sketch //removeUnique = 2: supress k-mers not specified in the file the same as max supression this.range = range; if (removeUnique<0 || removeUnique>2)
// Path: src/main/java/edu/umd/marbl/mhap/impl/MhapRuntimeException.java // public class MhapRuntimeException extends RuntimeException // { // // /** // * // */ // private static final long serialVersionUID = 56387323839744808L; // // public MhapRuntimeException() // { // super(); // } // // public MhapRuntimeException(String message, Throwable cause) // { // super(message, cause); // } // // public MhapRuntimeException(String message) // { // super(message); // } // // public MhapRuntimeException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/edu/umd/marbl/mhap/sketch/FrequencyCounts.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.google.common.hash.BloomFilter; import edu.umd.marbl.mhap.impl.MhapRuntimeException; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.io.BufferedReader; import java.io.IOException; /* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.umd.marbl.mhap.sketch; public final class FrequencyCounts { private final double filterCutoff; private final Map<Long,Double> fractionCounts; private final Set<Integer> kmerSizes; private final double maxIdfValue; private final double maxValue; private final double minIdfValue; private final double minValue; private final boolean noTf; private final double offset; private final double range; private final int removeUnique; private final BloomFilter<Long> validMers; public FrequencyCounts(BufferedReader bf, double filterCutoff, double offset, int removeUnique, boolean noTf, int numThreads, double range, boolean doReverseCompliment) throws IOException { //removeUnique = 0: do nothing extra to k-mers not specified in the file //removeUnique = 1: remove k-mers not specified in the file from the sketch //removeUnique = 2: supress k-mers not specified in the file the same as max supression this.range = range; if (removeUnique<0 || removeUnique>2)
throw new MhapRuntimeException("Unknown removeUnique option "+removeUnique+".");