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
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestSAMHeaderReader.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // }
import htsjdk.samtools.*; import htsjdk.samtools.cram.CRAMException; import org.apache.hadoop.conf.Configuration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.InputStream; import java.net.URI; import static org.junit.Assert.assertEquals;
package org.seqdoop.hadoop_bam; public class TestSAMHeaderReader { @Rule public ExpectedException thrown= ExpectedException.none(); @Test public void testBAMHeaderReaderNoReference() throws Exception { final Configuration conf = new Configuration(); InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("test.bam"); final SamReader samReader = SamReaderFactory.makeDefault().open(SamInputResource.of(inputStream)); int sequenceCount = samReader.getFileHeader().getSequenceDictionary().size(); samReader.close(); inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("test.bam");
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestSAMHeaderReader.java import htsjdk.samtools.*; import htsjdk.samtools.cram.CRAMException; import org.apache.hadoop.conf.Configuration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.InputStream; import java.net.URI; import static org.junit.Assert.assertEquals; package org.seqdoop.hadoop_bam; public class TestSAMHeaderReader { @Rule public ExpectedException thrown= ExpectedException.none(); @Test public void testBAMHeaderReaderNoReference() throws Exception { final Configuration conf = new Configuration(); InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("test.bam"); final SamReader samReader = SamReaderFactory.makeDefault().open(SamInputResource.of(inputStream)); int sequenceCount = samReader.getFileHeader().getSequenceDictionary().size(); samReader.close(); inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("test.bam");
SAMFileHeader samHeader = SAMHeaderReader.readSAMHeaderFrom(inputStream, conf);
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/util/IntervalUtil.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // }
import com.google.common.collect.ImmutableList; import htsjdk.samtools.util.Interval; import org.apache.hadoop.conf.Configuration; import org.seqdoop.hadoop_bam.FormatException; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier;
package org.seqdoop.hadoop_bam.util; /** * Common utilities across different file formats. */ public final class IntervalUtil { // declared to prevent instantiation. private IntervalUtil() {} /** * Returns the list of intervals found in a string configuration property separated by colons. * @param conf the source configuration. * @param intervalPropertyName the property name holding the intervals. * @return {@code null} if there is no such a property in the configuration. * @throws NullPointerException if either input is null. */ public static List<Interval> getIntervals(final Configuration conf, final String intervalPropertyName) { final String intervalsProperty = conf.get(intervalPropertyName); if (intervalsProperty == null) { return null; } if (intervalsProperty.isEmpty()) { return ImmutableList.of(); } final List<Interval> intervals = new ArrayList<>(); for (final String s : intervalsProperty.split(",")) { final int lastColonIdx = s.lastIndexOf(':'); if (lastColonIdx < 0) {
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/util/IntervalUtil.java import com.google.common.collect.ImmutableList; import htsjdk.samtools.util.Interval; import org.apache.hadoop.conf.Configuration; import org.seqdoop.hadoop_bam.FormatException; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; package org.seqdoop.hadoop_bam.util; /** * Common utilities across different file formats. */ public final class IntervalUtil { // declared to prevent instantiation. private IntervalUtil() {} /** * Returns the list of intervals found in a string configuration property separated by colons. * @param conf the source configuration. * @param intervalPropertyName the property name holding the intervals. * @return {@code null} if there is no such a property in the configuration. * @throws NullPointerException if either input is null. */ public static List<Interval> getIntervals(final Configuration conf, final String intervalPropertyName) { final String intervalsProperty = conf.get(intervalPropertyName); if (intervalsProperty == null) { return null; } if (intervalsProperty.isEmpty()) { return ImmutableList.of(); } final List<Interval> intervals = new ArrayList<>(); for (final String s : intervalsProperty.split(",")) { final int lastColonIdx = s.lastIndexOf(':'); if (lastColonIdx < 0) {
throw new FormatException("no colon found in interval string: " + s);
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestSequencedFragment.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public class FormatConstants // { // /** // * Offset by which Sanger-style ASCII-encoded quality scores are shifted. // */ // public static final int SANGER_OFFSET = 33; // // /** // * Maximum encodable quality score for Sanger Phred+33 encoded base qualities. // * // * Range of legal values is [0,93], according to wikipedia on 10/9/2013: // * http://en.wikipedia.org/wiki/FASTQ_format#Quality // */ // public static final int SANGER_MAX = 93; // // /** // * Offset by which Illumina-style ASCII-encoded quality scores are shifted. // */ // public static final int ILLUMINA_OFFSET = 64; // // /** // * Maximum encodable quality score for Illumina Phred+64 encoded base qualities. // */ // public static final int ILLUMINA_MAX = 62; // // /** // * Encodings for base quality formats. // */ // public enum BaseQualityEncoding { Illumina, Sanger }; // // private FormatConstants() {} // no instantiation // // public static final String CONF_INPUT_BASE_QUALITY_ENCODING = "hbam.input.base-quality-encoding"; // public static final String CONF_INPUT_FILTER_FAILED_QC = "hbam.input.filter-failed-qc"; // } // // Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // }
import java.io.DataInput; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import org.apache.hadoop.io.Text; import org.junit.*; import static org.junit.Assert.*; import org.seqdoop.hadoop_bam.SequencedFragment; import org.seqdoop.hadoop_bam.FormatConstants; import org.seqdoop.hadoop_bam.FormatException; import java.io.IOException;
assertEquals(frag, cloneBySerialization(frag)); } @Test public void testToString() { String seq = "AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT"; String qual = "##############################"; frag.setSequence(new Text(seq)); frag.setQuality(new Text(qual)); frag.setInstrument("machine"); frag.setRunNumber(123); frag.setFlowcellId("flowcell"); frag.setLane(3); frag.setTile(1001); frag.setXpos(1234); frag.setYpos(4321); frag.setIndexSequence("CAT"); frag.setRead(1); assertEquals("machine\t123\tflowcell\t3\t1001\t1234\t4321\tCAT\t1\t" + seq + "\t" + qual + "\t1", frag.toString()); } @Test public void testVerifyQualitySangerOk() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("##############################"));
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public class FormatConstants // { // /** // * Offset by which Sanger-style ASCII-encoded quality scores are shifted. // */ // public static final int SANGER_OFFSET = 33; // // /** // * Maximum encodable quality score for Sanger Phred+33 encoded base qualities. // * // * Range of legal values is [0,93], according to wikipedia on 10/9/2013: // * http://en.wikipedia.org/wiki/FASTQ_format#Quality // */ // public static final int SANGER_MAX = 93; // // /** // * Offset by which Illumina-style ASCII-encoded quality scores are shifted. // */ // public static final int ILLUMINA_OFFSET = 64; // // /** // * Maximum encodable quality score for Illumina Phred+64 encoded base qualities. // */ // public static final int ILLUMINA_MAX = 62; // // /** // * Encodings for base quality formats. // */ // public enum BaseQualityEncoding { Illumina, Sanger }; // // private FormatConstants() {} // no instantiation // // public static final String CONF_INPUT_BASE_QUALITY_ENCODING = "hbam.input.base-quality-encoding"; // public static final String CONF_INPUT_FILTER_FAILED_QC = "hbam.input.filter-failed-qc"; // } // // Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestSequencedFragment.java import java.io.DataInput; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import org.apache.hadoop.io.Text; import org.junit.*; import static org.junit.Assert.*; import org.seqdoop.hadoop_bam.SequencedFragment; import org.seqdoop.hadoop_bam.FormatConstants; import org.seqdoop.hadoop_bam.FormatException; import java.io.IOException; assertEquals(frag, cloneBySerialization(frag)); } @Test public void testToString() { String seq = "AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT"; String qual = "##############################"; frag.setSequence(new Text(seq)); frag.setQuality(new Text(qual)); frag.setInstrument("machine"); frag.setRunNumber(123); frag.setFlowcellId("flowcell"); frag.setLane(3); frag.setTile(1001); frag.setXpos(1234); frag.setYpos(4321); frag.setIndexSequence("CAT"); frag.setRead(1); assertEquals("machine\t123\tflowcell\t3\t1001\t1234\t4321\tCAT\t1\t" + seq + "\t" + qual + "\t1", frag.toString()); } @Test public void testVerifyQualitySangerOk() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("##############################"));
assertEquals(-1, SequencedFragment.verifyQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Sanger));
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestSequencedFragment.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public class FormatConstants // { // /** // * Offset by which Sanger-style ASCII-encoded quality scores are shifted. // */ // public static final int SANGER_OFFSET = 33; // // /** // * Maximum encodable quality score for Sanger Phred+33 encoded base qualities. // * // * Range of legal values is [0,93], according to wikipedia on 10/9/2013: // * http://en.wikipedia.org/wiki/FASTQ_format#Quality // */ // public static final int SANGER_MAX = 93; // // /** // * Offset by which Illumina-style ASCII-encoded quality scores are shifted. // */ // public static final int ILLUMINA_OFFSET = 64; // // /** // * Maximum encodable quality score for Illumina Phred+64 encoded base qualities. // */ // public static final int ILLUMINA_MAX = 62; // // /** // * Encodings for base quality formats. // */ // public enum BaseQualityEncoding { Illumina, Sanger }; // // private FormatConstants() {} // no instantiation // // public static final String CONF_INPUT_BASE_QUALITY_ENCODING = "hbam.input.base-quality-encoding"; // public static final String CONF_INPUT_FILTER_FAILED_QC = "hbam.input.filter-failed-qc"; // } // // Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // }
import java.io.DataInput; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import org.apache.hadoop.io.Text; import org.junit.*; import static org.junit.Assert.*; import org.seqdoop.hadoop_bam.SequencedFragment; import org.seqdoop.hadoop_bam.FormatConstants; import org.seqdoop.hadoop_bam.FormatException; import java.io.IOException;
frag.setQuality(new Text("zzz=zzzzzzzzzzzzzzzzzzzzzzzzzz")); assertEquals(3, SequencedFragment.verifyQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Illumina)); } @Test public void testConvertQualityIlluminaToSanger() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Illumina, FormatConstants.BaseQualityEncoding.Sanger); assertEquals("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[", frag.getQuality().toString()); } @Test public void testConvertQualitySangerToIllumina() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Sanger, FormatConstants.BaseQualityEncoding.Illumina); assertEquals("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", frag.getQuality().toString()); } @Test(expected=IllegalArgumentException.class) public void testConvertQualityNoop() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Sanger, FormatConstants.BaseQualityEncoding.Sanger); }
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public class FormatConstants // { // /** // * Offset by which Sanger-style ASCII-encoded quality scores are shifted. // */ // public static final int SANGER_OFFSET = 33; // // /** // * Maximum encodable quality score for Sanger Phred+33 encoded base qualities. // * // * Range of legal values is [0,93], according to wikipedia on 10/9/2013: // * http://en.wikipedia.org/wiki/FASTQ_format#Quality // */ // public static final int SANGER_MAX = 93; // // /** // * Offset by which Illumina-style ASCII-encoded quality scores are shifted. // */ // public static final int ILLUMINA_OFFSET = 64; // // /** // * Maximum encodable quality score for Illumina Phred+64 encoded base qualities. // */ // public static final int ILLUMINA_MAX = 62; // // /** // * Encodings for base quality formats. // */ // public enum BaseQualityEncoding { Illumina, Sanger }; // // private FormatConstants() {} // no instantiation // // public static final String CONF_INPUT_BASE_QUALITY_ENCODING = "hbam.input.base-quality-encoding"; // public static final String CONF_INPUT_FILTER_FAILED_QC = "hbam.input.filter-failed-qc"; // } // // Path: src/main/java/org/seqdoop/hadoop_bam/FormatException.java // public class FormatException extends RuntimeException // { // private static final long serialVersionUID = 1L; // public FormatException(String msg) // { // super(msg); // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestSequencedFragment.java import java.io.DataInput; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import org.apache.hadoop.io.Text; import org.junit.*; import static org.junit.Assert.*; import org.seqdoop.hadoop_bam.SequencedFragment; import org.seqdoop.hadoop_bam.FormatConstants; import org.seqdoop.hadoop_bam.FormatException; import java.io.IOException; frag.setQuality(new Text("zzz=zzzzzzzzzzzzzzzzzzzzzzzzzz")); assertEquals(3, SequencedFragment.verifyQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Illumina)); } @Test public void testConvertQualityIlluminaToSanger() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Illumina, FormatConstants.BaseQualityEncoding.Sanger); assertEquals("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[", frag.getQuality().toString()); } @Test public void testConvertQualitySangerToIllumina() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Sanger, FormatConstants.BaseQualityEncoding.Illumina); assertEquals("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", frag.getQuality().toString()); } @Test(expected=IllegalArgumentException.class) public void testConvertQualityNoop() { frag.setSequence(new Text("AGTAGTAGTAGTAGTAGTAGTAGTAGTAGT")); frag.setQuality(new Text("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[")); SequencedFragment.convertQuality(frag.getQuality(), FormatConstants.BaseQualityEncoding.Sanger, FormatConstants.BaseQualityEncoding.Sanger); }
@Test(expected=FormatException.class)
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestConfHelper.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // }
import org.seqdoop.hadoop_bam.util.ConfHelper; import org.junit.*; import static org.junit.Assert.*; import org.apache.hadoop.conf.Configuration;
// Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; public class TestConfHelper { @Test public void testParseBooleanValidValues() {
// Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestConfHelper.java import org.seqdoop.hadoop_bam.util.ConfHelper; import org.junit.*; import static org.junit.Assert.*; import org.apache.hadoop.conf.Configuration; // Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; public class TestConfHelper { @Test public void testParseBooleanValidValues() {
assertTrue(ConfHelper.parseBoolean("true", false));
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/BCFRecordWriter.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/WrapSeekable.java // public class WrapSeekable<S extends InputStream & Seekable> // extends SeekableStream // { // private final S stm; // private final long len; // private final Path path; // // public WrapSeekable(final S s, long length, Path p) { // stm = s; // len = length; // path = p; // } // // /** A helper for the common use case. */ // public static WrapSeekable<FSDataInputStream> openPath( // FileSystem fs, Path p) throws IOException // { // return new WrapSeekable<FSDataInputStream>( // fs.open(p), fs.getFileStatus(p).getLen(), p); // } // public static WrapSeekable<FSDataInputStream> openPath( // Configuration conf, Path path) throws IOException // { // return openPath(path.getFileSystem(conf), path); // } // // @Override public String getSource() { return path.toString(); } // @Override public long length () { return len; } // // @Override public long position() throws IOException { return stm.getPos(); } // @Override public void close() throws IOException { stm.close(); } // @Override public boolean eof () throws IOException { // return stm.getPos() == length(); // } // @Override public void seek(long pos) throws IOException { // stm.seek(pos); // } // @Override public int read() throws IOException { // return stm.read(); // } // @Override public int read(byte[] buf, int offset, int len) // throws IOException // { // return stm.read(buf, offset, len); // } // }
import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import htsjdk.variant.variantcontext.GenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.writer.Options; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder; import htsjdk.variant.vcf.VCFHeader; import org.seqdoop.hadoop_bam.util.VCFHeaderReader; import org.seqdoop.hadoop_bam.util.WrapSeekable; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import htsjdk.samtools.util.BlockCompressedOutputStream; import org.apache.hadoop.conf.Configuration;
// Copyright (c) 2013 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2013-06-28 15:58:08 package org.seqdoop.hadoop_bam; /** A base {@link RecordWriter} for compressed BCF. * * <p>Handles the output stream, writing the header if requested, and provides * the {@link #writeRecord} function for subclasses.</p> */ public abstract class BCFRecordWriter<K> extends RecordWriter<K,VariantContextWritable> { private VariantContextWriter writer; private LazyVCFGenotypesContext.HeaderDataCache vcfHeaderDataCache = new LazyVCFGenotypesContext.HeaderDataCache(); private LazyBCFGenotypesContext.HeaderDataCache bcfHeaderDataCache = new LazyBCFGenotypesContext.HeaderDataCache(); /** A VCF header is read from the input Path, which should refer to a VCF or * BCF file. */ public BCFRecordWriter( Path output, Path input, boolean writeHeader, TaskAttemptContext ctx) throws IOException {
// Path: src/main/java/org/seqdoop/hadoop_bam/util/WrapSeekable.java // public class WrapSeekable<S extends InputStream & Seekable> // extends SeekableStream // { // private final S stm; // private final long len; // private final Path path; // // public WrapSeekable(final S s, long length, Path p) { // stm = s; // len = length; // path = p; // } // // /** A helper for the common use case. */ // public static WrapSeekable<FSDataInputStream> openPath( // FileSystem fs, Path p) throws IOException // { // return new WrapSeekable<FSDataInputStream>( // fs.open(p), fs.getFileStatus(p).getLen(), p); // } // public static WrapSeekable<FSDataInputStream> openPath( // Configuration conf, Path path) throws IOException // { // return openPath(path.getFileSystem(conf), path); // } // // @Override public String getSource() { return path.toString(); } // @Override public long length () { return len; } // // @Override public long position() throws IOException { return stm.getPos(); } // @Override public void close() throws IOException { stm.close(); } // @Override public boolean eof () throws IOException { // return stm.getPos() == length(); // } // @Override public void seek(long pos) throws IOException { // stm.seek(pos); // } // @Override public int read() throws IOException { // return stm.read(); // } // @Override public int read(byte[] buf, int offset, int len) // throws IOException // { // return stm.read(buf, offset, len); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/BCFRecordWriter.java import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import htsjdk.variant.variantcontext.GenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.writer.Options; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder; import htsjdk.variant.vcf.VCFHeader; import org.seqdoop.hadoop_bam.util.VCFHeaderReader; import org.seqdoop.hadoop_bam.util.WrapSeekable; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import htsjdk.samtools.util.BlockCompressedOutputStream; import org.apache.hadoop.conf.Configuration; // Copyright (c) 2013 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2013-06-28 15:58:08 package org.seqdoop.hadoop_bam; /** A base {@link RecordWriter} for compressed BCF. * * <p>Handles the output stream, writing the header if requested, and provides * the {@link #writeRecord} function for subclasses.</p> */ public abstract class BCFRecordWriter<K> extends RecordWriter<K,VariantContextWritable> { private VariantContextWriter writer; private LazyVCFGenotypesContext.HeaderDataCache vcfHeaderDataCache = new LazyVCFGenotypesContext.HeaderDataCache(); private LazyBCFGenotypesContext.HeaderDataCache bcfHeaderDataCache = new LazyBCFGenotypesContext.HeaderDataCache(); /** A VCF header is read from the input Path, which should refer to a VCF or * BCF file. */ public BCFRecordWriter( Path output, Path input, boolean writeHeader, TaskAttemptContext ctx) throws IOException {
final WrapSeekable in =
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/SAMRecordWriter.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // }
import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.IOException; import java.io.OutputStream; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMTextWriter; import org.apache.hadoop.fs.Path;
// Copyright (c) 2010 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2012-02-23 12:42:49 package org.seqdoop.hadoop_bam; /** A base {@link RecordWriter} for SAM records. * * <p>Handles the output stream, writing the header if requested, and provides * the {@link #writeAlignment} function for subclasses.</p> */ public abstract class SAMRecordWriter<K> extends RecordWriter<K,SAMRecordWritable> { private SAMTextWriter writer; private SAMFileHeader header; /** A SAMFileHeader is read from the input Path. */ public SAMRecordWriter( Path output, Path input, boolean writeHeader, TaskAttemptContext ctx) throws IOException { init( output,
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/SAMRecordWriter.java import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.IOException; import java.io.OutputStream; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMTextWriter; import org.apache.hadoop.fs.Path; // Copyright (c) 2010 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2012-02-23 12:42:49 package org.seqdoop.hadoop_bam; /** A base {@link RecordWriter} for SAM records. * * <p>Handles the output stream, writing the header if requested, and provides * the {@link #writeAlignment} function for subclasses.</p> */ public abstract class SAMRecordWriter<K> extends RecordWriter<K,SAMRecordWritable> { private SAMTextWriter writer; private SAMFileHeader header; /** A SAMFileHeader is read from the input Path. */ public SAMRecordWriter( Path output, Path input, boolean writeHeader, TaskAttemptContext ctx) throws IOException { init( output,
SAMHeaderReader.readSAMHeaderFrom(input, ctx.getConfiguration()),
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestBAMSplitGuesser.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/WrapSeekable.java // public class WrapSeekable<S extends InputStream & Seekable> // extends SeekableStream // { // private final S stm; // private final long len; // private final Path path; // // public WrapSeekable(final S s, long length, Path p) { // stm = s; // len = length; // path = p; // } // // /** A helper for the common use case. */ // public static WrapSeekable<FSDataInputStream> openPath( // FileSystem fs, Path p) throws IOException // { // return new WrapSeekable<FSDataInputStream>( // fs.open(p), fs.getFileStatus(p).getLen(), p); // } // public static WrapSeekable<FSDataInputStream> openPath( // Configuration conf, Path path) throws IOException // { // return openPath(path.getFileSystem(conf), path); // } // // @Override public String getSource() { return path.toString(); } // @Override public long length () { return len; } // // @Override public long position() throws IOException { return stm.getPos(); } // @Override public void close() throws IOException { stm.close(); } // @Override public boolean eof () throws IOException { // return stm.getPos() == length(); // } // @Override public void seek(long pos) throws IOException { // stm.seek(pos); // } // @Override public int read() throws IOException { // return stm.read(); // } // @Override public int read(byte[] buf, int offset, int len) // throws IOException // { // return stm.read(buf, offset, len); // } // }
import htsjdk.samtools.SAMUtils; import htsjdk.samtools.seekablestream.SeekableStream; import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.Test; import org.seqdoop.hadoop_bam.util.WrapSeekable; import static org.junit.Assert.assertEquals;
package org.seqdoop.hadoop_bam; public class TestBAMSplitGuesser { @Test public void test() throws Exception { Configuration conf = new Configuration(); String bam = getClass().getClassLoader().getResource("test.bam").getFile();
// Path: src/main/java/org/seqdoop/hadoop_bam/util/WrapSeekable.java // public class WrapSeekable<S extends InputStream & Seekable> // extends SeekableStream // { // private final S stm; // private final long len; // private final Path path; // // public WrapSeekable(final S s, long length, Path p) { // stm = s; // len = length; // path = p; // } // // /** A helper for the common use case. */ // public static WrapSeekable<FSDataInputStream> openPath( // FileSystem fs, Path p) throws IOException // { // return new WrapSeekable<FSDataInputStream>( // fs.open(p), fs.getFileStatus(p).getLen(), p); // } // public static WrapSeekable<FSDataInputStream> openPath( // Configuration conf, Path path) throws IOException // { // return openPath(path.getFileSystem(conf), path); // } // // @Override public String getSource() { return path.toString(); } // @Override public long length () { return len; } // // @Override public long position() throws IOException { return stm.getPos(); } // @Override public void close() throws IOException { stm.close(); } // @Override public boolean eof () throws IOException { // return stm.getPos() == length(); // } // @Override public void seek(long pos) throws IOException { // stm.seek(pos); // } // @Override public int read() throws IOException { // return stm.read(); // } // @Override public int read(byte[] buf, int offset, int len) // throws IOException // { // return stm.read(buf, offset, len); // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestBAMSplitGuesser.java import htsjdk.samtools.SAMUtils; import htsjdk.samtools.seekablestream.SeekableStream; import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.Test; import org.seqdoop.hadoop_bam.util.WrapSeekable; import static org.junit.Assert.assertEquals; package org.seqdoop.hadoop_bam; public class TestBAMSplitGuesser { @Test public void test() throws Exception { Configuration conf = new Configuration(); String bam = getClass().getClassLoader().getResource("test.bam").getFile();
SeekableStream ss = WrapSeekable.openPath(conf, new Path(bam));
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/KeyIgnoringCRAMOutputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // }
import java.io.IOException; import java.io.InputStream; import htsjdk.samtools.SAMFileHeader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader;
package org.seqdoop.hadoop_bam; /** Writes only the BAM records, not the key. * * <p>A {@link SAMFileHeader} must be provided via {@link #setSAMHeader} or * {@link #readSAMHeaderFrom} before {@link #getRecordWriter} is called.</p> * * <p>By default, writes the SAM header to the output file(s). This * can be disabled, because in distributed usage one often ends up with (and, * for decent performance, wants to end up with) the output split into multiple * parts, which are easier to concatenate if the header is not present in each * file.</p> */ public class KeyIgnoringCRAMOutputFormat<K> extends CRAMOutputFormat<K> { protected SAMFileHeader header; private boolean writeHeader = true; public KeyIgnoringCRAMOutputFormat() {} /** Whether the header will be written or not. */ public boolean getWriteHeader() { return writeHeader; } /** Set whether the header will be written or not. */ public void setWriteHeader(boolean b) { writeHeader = b; } public SAMFileHeader getSAMHeader() { return header; } public void setSAMHeader(SAMFileHeader header) { this.header = header; } public void readSAMHeaderFrom(Path path, Configuration conf) throws IOException {
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/KeyIgnoringCRAMOutputFormat.java import java.io.IOException; import java.io.InputStream; import htsjdk.samtools.SAMFileHeader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; package org.seqdoop.hadoop_bam; /** Writes only the BAM records, not the key. * * <p>A {@link SAMFileHeader} must be provided via {@link #setSAMHeader} or * {@link #readSAMHeaderFrom} before {@link #getRecordWriter} is called.</p> * * <p>By default, writes the SAM header to the output file(s). This * can be disabled, because in distributed usage one often ends up with (and, * for decent performance, wants to end up with) the output split into multiple * parts, which are easier to concatenate if the header is not present in each * file.</p> */ public class KeyIgnoringCRAMOutputFormat<K> extends CRAMOutputFormat<K> { protected SAMFileHeader header; private boolean writeHeader = true; public KeyIgnoringCRAMOutputFormat() {} /** Whether the header will be written or not. */ public boolean getWriteHeader() { return writeHeader; } /** Set whether the header will be written or not. */ public void setWriteHeader(boolean b) { writeHeader = b; } public SAMFileHeader getSAMHeader() { return header; } public void setSAMHeader(SAMFileHeader header) { this.header = header; } public void readSAMHeaderFrom(Path path, Configuration conf) throws IOException {
this.header = SAMHeaderReader.readSAMHeaderFrom(path, conf);
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/TestVCFInputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/BGZFCodec.java // public class BGZFCodec extends GzipCodec implements SplittableCompressionCodec { // // public static final String DEFAULT_EXTENSION = ".bgz"; // // @Override // public CompressionOutputStream createOutputStream(OutputStream out) throws IOException { // return new BGZFCompressionOutputStream(out); // } // // // compressors are not used, so ignore/return null // // @Override // public CompressionOutputStream createOutputStream(OutputStream out, // Compressor compressor) throws IOException { // return createOutputStream(out); // compressors are not used, so ignore // } // // @Override // public Class<? extends Compressor> getCompressorType() { // return null; // compressors are not used, so return null // } // // @Override // public Compressor createCompressor() { // return null; // compressors are not used, so return null // } // // @Override // public SplitCompressionInputStream createInputStream(InputStream seekableIn, // Decompressor decompressor, long start, long end, READ_MODE readMode) throws IOException { // BGZFSplitGuesser splitGuesser = new BGZFSplitGuesser(seekableIn); // long adjustedStart = splitGuesser.guessNextBGZFBlockStart(start, end); // ((Seekable)seekableIn).seek(adjustedStart); // return new BGZFSplitCompressionInputStream(seekableIn, adjustedStart, end); // } // // // fall back to GzipCodec for input streams without a start position // // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // }
import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import htsjdk.samtools.util.Interval; import htsjdk.variant.vcf.VCFFileReader; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.*; import htsjdk.variant.variantcontext.VariantContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.seqdoop.hadoop_bam.util.BGZFCodec; import org.seqdoop.hadoop_bam.util.BGZFEnhancedGzipCodec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
this.interval = interval; } @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[][] { {"test.vcf", NUM_SPLITS.ANY, null}, {"test.vcf.gz", NUM_SPLITS.EXACTLY_ONE, null}, {"test.vcf.bgzf.gz", NUM_SPLITS.ANY, null}, // BCF tests currently fail due to https://github.com/samtools/htsjdk/issues/507 // {"test.uncompressed.bcf", NUM_SPLITS.ANY, null}, // {"test.bgzf.bcf", NUM_SPLITS.ANY, null}, {"HiSeq.10000.vcf", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.gz", NUM_SPLITS.EXACTLY_ONE, null}, {"HiSeq.10000.vcf.bgzf.gz", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.bgzf.gz", NUM_SPLITS.EXACTLY_ONE, new Interval("chr1", 2700000, 2800000)}, // chosen to fall in one split {"HiSeq.10000.vcf.bgz", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.bgz", NUM_SPLITS.EXACTLY_ONE, new Interval("chr1", 2700000, 2800000)} // chosen to fall in one split }); } @Before public void setup() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException, NoSuchFieldException { Configuration conf = new Configuration(); String input_file = ClassLoader.getSystemClassLoader().getResource(filename).getFile(); conf.set("hadoopbam.vcf.trust-exts", "true"); conf.set("mapred.input.dir", "file://" + input_file); conf.setStrings("io.compression.codecs", BGZFEnhancedGzipCodec.class.getCanonicalName(),
// Path: src/main/java/org/seqdoop/hadoop_bam/util/BGZFCodec.java // public class BGZFCodec extends GzipCodec implements SplittableCompressionCodec { // // public static final String DEFAULT_EXTENSION = ".bgz"; // // @Override // public CompressionOutputStream createOutputStream(OutputStream out) throws IOException { // return new BGZFCompressionOutputStream(out); // } // // // compressors are not used, so ignore/return null // // @Override // public CompressionOutputStream createOutputStream(OutputStream out, // Compressor compressor) throws IOException { // return createOutputStream(out); // compressors are not used, so ignore // } // // @Override // public Class<? extends Compressor> getCompressorType() { // return null; // compressors are not used, so return null // } // // @Override // public Compressor createCompressor() { // return null; // compressors are not used, so return null // } // // @Override // public SplitCompressionInputStream createInputStream(InputStream seekableIn, // Decompressor decompressor, long start, long end, READ_MODE readMode) throws IOException { // BGZFSplitGuesser splitGuesser = new BGZFSplitGuesser(seekableIn); // long adjustedStart = splitGuesser.guessNextBGZFBlockStart(start, end); // ((Seekable)seekableIn).seek(adjustedStart); // return new BGZFSplitCompressionInputStream(seekableIn, adjustedStart, end); // } // // // fall back to GzipCodec for input streams without a start position // // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/TestVCFInputFormat.java import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import htsjdk.samtools.util.Interval; import htsjdk.variant.vcf.VCFFileReader; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.*; import htsjdk.variant.variantcontext.VariantContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.seqdoop.hadoop_bam.util.BGZFCodec; import org.seqdoop.hadoop_bam.util.BGZFEnhancedGzipCodec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; this.interval = interval; } @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[][] { {"test.vcf", NUM_SPLITS.ANY, null}, {"test.vcf.gz", NUM_SPLITS.EXACTLY_ONE, null}, {"test.vcf.bgzf.gz", NUM_SPLITS.ANY, null}, // BCF tests currently fail due to https://github.com/samtools/htsjdk/issues/507 // {"test.uncompressed.bcf", NUM_SPLITS.ANY, null}, // {"test.bgzf.bcf", NUM_SPLITS.ANY, null}, {"HiSeq.10000.vcf", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.gz", NUM_SPLITS.EXACTLY_ONE, null}, {"HiSeq.10000.vcf.bgzf.gz", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.bgzf.gz", NUM_SPLITS.EXACTLY_ONE, new Interval("chr1", 2700000, 2800000)}, // chosen to fall in one split {"HiSeq.10000.vcf.bgz", NUM_SPLITS.MORE_THAN_ONE, null}, {"HiSeq.10000.vcf.bgz", NUM_SPLITS.EXACTLY_ONE, new Interval("chr1", 2700000, 2800000)} // chosen to fall in one split }); } @Before public void setup() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException, NoSuchFieldException { Configuration conf = new Configuration(); String input_file = ClassLoader.getSystemClassLoader().getResource(filename).getFile(); conf.set("hadoopbam.vcf.trust-exts", "true"); conf.set("mapred.input.dir", "file://" + input_file); conf.setStrings("io.compression.codecs", BGZFEnhancedGzipCodec.class.getCanonicalName(),
BGZFCodec.class.getCanonicalName());
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/FastqInputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // }
import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.util.regex.*; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.*; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
// Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; public class FastqInputFormat extends FileInputFormat<Text,SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.fastq-input.base-quality-encoding"; public static final String CONF_FILTER_FAILED_QC = "hbam.fastq-input.filter-failed-qc"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "sanger"; public static class FastqRecordReader extends RecordReader<Text,SequencedFragment> { /* * fastq format: * <fastq> := <block>+ * <block> := @<seqname>\n<seq>\n+[<seqname>]\n<qual>\n * <seqname> := [A-Za-z0-9_.:-]+ * <seq> := [A-Za-z\n\.~]+ * <qual> := [!-~\n]+ * * LP: this format is broken, no? You can have multi-line sequence and quality strings, * and the quality encoding includes '@' in its valid character range. So how should one * distinguish between \n@ as a record delimiter and and \n@ as part of a multi-line * quality string? * * For now I'm going to assume single-line sequences. This works for our sequencing * application. We'll see if someone complains in other applications. */ // start: first valid data index private long start; // end: first index value beyond the slice, i.e. slice is in range [start,end) private long end; // pos: current position in file private long pos; // file: the file being read private Path file; private LineReader lineReader; private InputStream inputStream; private Text currentKey = new Text(); private SequencedFragment currentValue = new SequencedFragment(); /* If true, will scan the identifier for read data as specified in the Casava * users' guide v1.8: * @<instrument>:<run number>:<flowcell ID>:<lane>:<tile>:<x-pos>:<y-pos> <read>:<is filtered>:<control number>:<index sequence> * After the first name that doesn't match lookForIlluminaIdentifier will be * set to false and no further scanning will be done. */ private boolean lookForIlluminaIdentifier = true; private static final Pattern ILLUMINA_PATTERN = Pattern.compile("([^:]+):(\\d+):([^:]*):(\\d+):(\\d+):(-?\\d+):(-?\\d+)\\s+([123]):([YN]):(\\d+):(.*)"); private Text buffer = new Text();
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/FastqInputFormat.java import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.util.regex.*; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.*; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; // Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; public class FastqInputFormat extends FileInputFormat<Text,SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.fastq-input.base-quality-encoding"; public static final String CONF_FILTER_FAILED_QC = "hbam.fastq-input.filter-failed-qc"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "sanger"; public static class FastqRecordReader extends RecordReader<Text,SequencedFragment> { /* * fastq format: * <fastq> := <block>+ * <block> := @<seqname>\n<seq>\n+[<seqname>]\n<qual>\n * <seqname> := [A-Za-z0-9_.:-]+ * <seq> := [A-Za-z\n\.~]+ * <qual> := [!-~\n]+ * * LP: this format is broken, no? You can have multi-line sequence and quality strings, * and the quality encoding includes '@' in its valid character range. So how should one * distinguish between \n@ as a record delimiter and and \n@ as part of a multi-line * quality string? * * For now I'm going to assume single-line sequences. This works for our sequencing * application. We'll see if someone complains in other applications. */ // start: first valid data index private long start; // end: first index value beyond the slice, i.e. slice is in range [start,end) private long end; // pos: current position in file private long pos; // file: the file being read private Path file; private LineReader lineReader; private InputStream inputStream; private Text currentKey = new Text(); private SequencedFragment currentValue = new SequencedFragment(); /* If true, will scan the identifier for read data as specified in the Casava * users' guide v1.8: * @<instrument>:<run number>:<flowcell ID>:<lane>:<tile>:<x-pos>:<y-pos> <read>:<is filtered>:<control number>:<index sequence> * After the first name that doesn't match lookForIlluminaIdentifier will be * set to false and no further scanning will be done. */ private boolean lookForIlluminaIdentifier = true; private static final Pattern ILLUMINA_PATTERN = Pattern.compile("([^:]+):(\\d+):([^:]*):(\\d+):(\\d+):(-?\\d+):(-?\\d+)\\s+([123]):([YN]):(\\d+):(.*)"); private Text buffer = new Text();
private BaseQualityEncoding qualityEncoding;
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/FastqInputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // }
import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.util.regex.*; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.*; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
{ positionAtFirstRecord(fileIn); inputStream = fileIn; } else { // compressed file if (start != 0) throw new RuntimeException("Start position for compressed file is not 0! (found " + start + ")"); inputStream = codec.createInputStream(fileIn); end = Long.MAX_VALUE; // read until the end of the file } lineReader = new LineReader(inputStream); } protected void setConf(Configuration conf) { String encoding = conf.get(FastqInputFormat.CONF_BASE_QUALITY_ENCODING, conf.get(FormatConstants.CONF_INPUT_BASE_QUALITY_ENCODING, FastqInputFormat.CONF_BASE_QUALITY_ENCODING_DEFAULT)); if ("illumina".equals(encoding)) qualityEncoding = BaseQualityEncoding.Illumina; else if ("sanger".equals(encoding)) qualityEncoding = BaseQualityEncoding.Sanger; else throw new RuntimeException("Unknown input base quality encoding value " + encoding);
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/FastqInputFormat.java import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.util.regex.*; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.compress.*; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; { positionAtFirstRecord(fileIn); inputStream = fileIn; } else { // compressed file if (start != 0) throw new RuntimeException("Start position for compressed file is not 0! (found " + start + ")"); inputStream = codec.createInputStream(fileIn); end = Long.MAX_VALUE; // read until the end of the file } lineReader = new LineReader(inputStream); } protected void setConf(Configuration conf) { String encoding = conf.get(FastqInputFormat.CONF_BASE_QUALITY_ENCODING, conf.get(FormatConstants.CONF_INPUT_BASE_QUALITY_ENCODING, FastqInputFormat.CONF_BASE_QUALITY_ENCODING_DEFAULT)); if ("illumina".equals(encoding)) qualityEncoding = BaseQualityEncoding.Illumina; else if ("sanger".equals(encoding)) qualityEncoding = BaseQualityEncoding.Sanger; else throw new RuntimeException("Unknown input base quality encoding value " + encoding);
filterFailedQC = ConfHelper.parseBoolean(
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/KeyIgnoringAnySAMOutputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // }
import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.IOException; import java.io.InputStream; import htsjdk.samtools.SAMFileHeader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter;
// Copyright (c) 2010 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2010-08-11 12:19:23 package org.seqdoop.hadoop_bam; /** Writes only the SAM records, not the key. * * <p>A {@link SAMFileHeader} must be provided via {@link #setSAMHeader} or * {@link #readSAMHeaderFrom} before {@link #getRecordWriter} is called.</p> * * <p>By default, writes the SAM header to the output file(s). This * can be disabled, because in distributed usage one often ends up with (and, * for decent performance, wants to end up with) the output split into multiple * parts, which are easier to concatenate if the header is not present in each * file.</p> */ public class KeyIgnoringAnySAMOutputFormat<K> extends AnySAMOutputFormat<K> { protected SAMFileHeader header; /** Whether the header will be written, defaults to true.. */ public static final String WRITE_HEADER_PROPERTY = "hadoopbam.anysam.write-header"; public KeyIgnoringAnySAMOutputFormat(SAMFormat fmt) { super(fmt); } public KeyIgnoringAnySAMOutputFormat(Configuration conf) { super(conf); if (format == null) throw new IllegalArgumentException( "unknown SAM format: OUTPUT_SAM_FORMAT_PROPERTY not set"); } public KeyIgnoringAnySAMOutputFormat(Configuration conf, Path path) { super(conf); if (format == null) { format = SAMFormat.inferFromFilePath(path); if (format == null) throw new IllegalArgumentException("unknown SAM format: " + path); } } public SAMFileHeader getSAMHeader() { return header; } public void setSAMHeader(SAMFileHeader header) { this.header = header; } public void readSAMHeaderFrom(Path path, Configuration conf) throws IOException {
// Path: src/main/java/org/seqdoop/hadoop_bam/util/SAMHeaderReader.java // public final class SAMHeaderReader { // /** A String property corresponding to a ValidationStringency // * value. If set, the given stringency is used when any part of the // * Hadoop-BAM library reads SAM or BAM. // */ // public static final String VALIDATION_STRINGENCY_PROPERTY = // "hadoopbam.samheaderreader.validation-stringency"; // // public static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf) // throws IOException // { // InputStream i = path.getFileSystem(conf).open(path); // final SAMFileHeader h = readSAMHeaderFrom(i, conf); // i.close(); // return h; // } // // /** Does not close the stream. */ // public static SAMFileHeader readSAMHeaderFrom( // final InputStream in, final Configuration conf) // { // final ValidationStringency // stringency = getValidationStringency(conf); // SamReaderFactory readerFactory = SamReaderFactory.makeDefault() // .setOption(SamReaderFactory.Option.EAGERLY_DECODE, false) // .setUseAsyncIo(false); // if (stringency != null) { // readerFactory.validationStringency(stringency); // } // // final ReferenceSource refSource = getReferenceSource(conf); // if (null != refSource) { // readerFactory.referenceSource(refSource); // } // return readerFactory.open(SamInputResource.of(in)).getFileHeader(); // } // // public static ValidationStringency getValidationStringency( // final Configuration conf) // { // final String p = conf.get(VALIDATION_STRINGENCY_PROPERTY); // return p == null ? null : ValidationStringency.valueOf(p); // } // // public static ReferenceSource getReferenceSource( // final Configuration conf) // { // //TODO: There isn't anything particularly CRAM-specific about reference source or validation // // stringency other than that a reference source is required for CRAM files. We should move // // the reference source and validation stringency property names and utility methods out of // // CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting // // configuration params, but it would break backward compatibility with existing code that // // is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY. // final String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY); // return refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath)); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/KeyIgnoringAnySAMOutputFormat.java import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.seqdoop.hadoop_bam.util.SAMHeaderReader; import java.io.IOException; import java.io.InputStream; import htsjdk.samtools.SAMFileHeader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.RecordWriter; // Copyright (c) 2010 Aalto University // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2010-08-11 12:19:23 package org.seqdoop.hadoop_bam; /** Writes only the SAM records, not the key. * * <p>A {@link SAMFileHeader} must be provided via {@link #setSAMHeader} or * {@link #readSAMHeaderFrom} before {@link #getRecordWriter} is called.</p> * * <p>By default, writes the SAM header to the output file(s). This * can be disabled, because in distributed usage one often ends up with (and, * for decent performance, wants to end up with) the output split into multiple * parts, which are easier to concatenate if the header is not present in each * file.</p> */ public class KeyIgnoringAnySAMOutputFormat<K> extends AnySAMOutputFormat<K> { protected SAMFileHeader header; /** Whether the header will be written, defaults to true.. */ public static final String WRITE_HEADER_PROPERTY = "hadoopbam.anysam.write-header"; public KeyIgnoringAnySAMOutputFormat(SAMFormat fmt) { super(fmt); } public KeyIgnoringAnySAMOutputFormat(Configuration conf) { super(conf); if (format == null) throw new IllegalArgumentException( "unknown SAM format: OUTPUT_SAM_FORMAT_PROPERTY not set"); } public KeyIgnoringAnySAMOutputFormat(Configuration conf, Path path) { super(conf); if (format == null) { format = SAMFormat.inferFromFilePath(path); if (format == null) throw new IllegalArgumentException("unknown SAM format: " + path); } } public SAMFileHeader getSAMHeader() { return header; } public void setSAMHeader(SAMFileHeader header) { this.header = header; } public void readSAMHeaderFrom(Path path, Configuration conf) throws IOException {
this.header = SAMHeaderReader.readSAMHeaderFrom(path, conf);
HadoopGenomics/Hadoop-BAM
src/test/java/org/seqdoop/hadoop_bam/IntervalUtilTest.java
// Path: src/main/java/org/seqdoop/hadoop_bam/util/IntervalUtil.java // public final class IntervalUtil { // // // declared to prevent instantiation. // private IntervalUtil() {} // // /** // * Returns the list of intervals found in a string configuration property separated by colons. // * @param conf the source configuration. // * @param intervalPropertyName the property name holding the intervals. // * @return {@code null} if there is no such a property in the configuration. // * @throws NullPointerException if either input is null. // */ // public static List<Interval> getIntervals(final Configuration conf, final String intervalPropertyName) { // final String intervalsProperty = conf.get(intervalPropertyName); // if (intervalsProperty == null) { // return null; // } // if (intervalsProperty.isEmpty()) { // return ImmutableList.of(); // } // final List<Interval> intervals = new ArrayList<>(); // for (final String s : intervalsProperty.split(",")) { // final int lastColonIdx = s.lastIndexOf(':'); // if (lastColonIdx < 0) { // throw new FormatException("no colon found in interval string: " + s); // } // final int hyphenIdx = s.indexOf('-', lastColonIdx + 1); // if (hyphenIdx < 0) { // throw new FormatException("no hyphen found after colon interval string: " + s); // } // final String sequence = s.substring(0, lastColonIdx); // final int start = parseIntOrThrowFormatException(s.substring(lastColonIdx + 1, hyphenIdx), // "invalid start position", s); // final int stop = parseIntOrThrowFormatException(s.substring(hyphenIdx + 1), // "invalid stop position", s); // intervals.add(new Interval(sequence, start, stop)); // } // return intervals; // } // // private static int parseIntOrThrowFormatException(final String str, final String error, final String input) { // try { // return Integer.parseInt(str); // } catch (final NumberFormatException ex) { // throw new FormatException(error + " in interval '" + input + "': '" + str + "'"); // } // } // }
import htsjdk.samtools.util.Interval; import org.apache.hadoop.conf.Configuration; import org.junit.Assert; import org.junit.Test; import org.seqdoop.hadoop_bam.util.IntervalUtil; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.seqdoop.hadoop_bam; /** * Unit tests for {@link IntervalUtil}. */ public class IntervalUtilTest { @Test public void testInvalidIntervals() { final String[] invalidIntervals = { "chr1", // full sequence interval are not allowed. "chr1:12", // single position omitting stop is not allowed. "chr1,chr2:121-123", // , are not allowed anywhere "chr20:1,100-3,400", // , " " "MT:35+", // , until end of contig + is not allowed. "MT:13-31-1112", // too many positions. "MT:-2112", // forgot the start position! " MT : 113 - 1245" // blanks are not allowed either. }; for (final String interval : invalidIntervals) { final Configuration conf = new Configuration(); conf.set("prop-name", interval); try {
// Path: src/main/java/org/seqdoop/hadoop_bam/util/IntervalUtil.java // public final class IntervalUtil { // // // declared to prevent instantiation. // private IntervalUtil() {} // // /** // * Returns the list of intervals found in a string configuration property separated by colons. // * @param conf the source configuration. // * @param intervalPropertyName the property name holding the intervals. // * @return {@code null} if there is no such a property in the configuration. // * @throws NullPointerException if either input is null. // */ // public static List<Interval> getIntervals(final Configuration conf, final String intervalPropertyName) { // final String intervalsProperty = conf.get(intervalPropertyName); // if (intervalsProperty == null) { // return null; // } // if (intervalsProperty.isEmpty()) { // return ImmutableList.of(); // } // final List<Interval> intervals = new ArrayList<>(); // for (final String s : intervalsProperty.split(",")) { // final int lastColonIdx = s.lastIndexOf(':'); // if (lastColonIdx < 0) { // throw new FormatException("no colon found in interval string: " + s); // } // final int hyphenIdx = s.indexOf('-', lastColonIdx + 1); // if (hyphenIdx < 0) { // throw new FormatException("no hyphen found after colon interval string: " + s); // } // final String sequence = s.substring(0, lastColonIdx); // final int start = parseIntOrThrowFormatException(s.substring(lastColonIdx + 1, hyphenIdx), // "invalid start position", s); // final int stop = parseIntOrThrowFormatException(s.substring(hyphenIdx + 1), // "invalid stop position", s); // intervals.add(new Interval(sequence, start, stop)); // } // return intervals; // } // // private static int parseIntOrThrowFormatException(final String str, final String error, final String input) { // try { // return Integer.parseInt(str); // } catch (final NumberFormatException ex) { // throw new FormatException(error + " in interval '" + input + "': '" + str + "'"); // } // } // } // Path: src/test/java/org/seqdoop/hadoop_bam/IntervalUtilTest.java import htsjdk.samtools.util.Interval; import org.apache.hadoop.conf.Configuration; import org.junit.Assert; import org.junit.Test; import org.seqdoop.hadoop_bam.util.IntervalUtil; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; package org.seqdoop.hadoop_bam; /** * Unit tests for {@link IntervalUtil}. */ public class IntervalUtilTest { @Test public void testInvalidIntervals() { final String[] invalidIntervals = { "chr1", // full sequence interval are not allowed. "chr1:12", // single position omitting stop is not allowed. "chr1,chr2:121-123", // , are not allowed anywhere "chr20:1,100-3,400", // , " " "MT:35+", // , until end of contig + is not allowed. "MT:13-31-1112", // too many positions. "MT:-2112", // forgot the start position! " MT : 113 - 1245" // blanks are not allowed either. }; for (final String interval : invalidIntervals) { final Configuration conf = new Configuration(); conf.set("prop-name", interval); try {
IntervalUtil.getIntervals(conf, "prop-name");
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/FastqOutputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger };
import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.ReflectionUtils; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import java.io.DataOutputStream; import java.io.OutputStream; import java.io.IOException; import java.nio.charset.Charset; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem;
// Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; /** * Output format for the fastq format. */ // If a key is provided with the SequencedFragment, the key is used as the sequence // id and the meta-info from the SequencedFragment (if any) is dropped. // If the key is null, then the format will attempt to create an // Illumina-style fastq id as specified in the Casava users' guide v1.8: // @instrument:run number:flowcell ID:lane:tile:x-pos:y-pos \s+ read:is filtered:control number:index sequence // public class FastqOutputFormat extends TextOutputFormat<Text, SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.fastq-output.base-quality-encoding"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "sanger"; public static final Charset UTF8 = Charset.forName("UTF8"); static final byte[] PLUS_LINE; static { try { PLUS_LINE = "\n+\n".getBytes("us-ascii"); } catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("us-ascii encoding not supported!"); } } public static class FastqRecordWriter extends RecordWriter<Text,SequencedFragment> { protected StringBuilder sBuilder = new StringBuilder(800); protected Text buffer = new Text(); protected OutputStream out;
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // Path: src/main/java/org/seqdoop/hadoop_bam/FastqOutputFormat.java import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.ReflectionUtils; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import java.io.DataOutputStream; import java.io.OutputStream; import java.io.IOException; import java.nio.charset.Charset; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; // Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; /** * Output format for the fastq format. */ // If a key is provided with the SequencedFragment, the key is used as the sequence // id and the meta-info from the SequencedFragment (if any) is dropped. // If the key is null, then the format will attempt to create an // Illumina-style fastq id as specified in the Casava users' guide v1.8: // @instrument:run number:flowcell ID:lane:tile:x-pos:y-pos \s+ read:is filtered:control number:index sequence // public class FastqOutputFormat extends TextOutputFormat<Text, SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.fastq-output.base-quality-encoding"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "sanger"; public static final Charset UTF8 = Charset.forName("UTF8"); static final byte[] PLUS_LINE; static { try { PLUS_LINE = "\n+\n".getBytes("us-ascii"); } catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("us-ascii encoding not supported!"); } } public static class FastqRecordWriter extends RecordWriter<Text,SequencedFragment> { protected StringBuilder sBuilder = new StringBuilder(800); protected Text buffer = new Text(); protected OutputStream out;
protected BaseQualityEncoding baseQualityFormat;
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/QseqInputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // }
import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.CharacterCodingException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path;
// Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; /** * Reads the Illumina qseq sequence format. * Key: instrument, run number, lane, tile, xpos, ypos, read number, delimited by ':' characters. * Value: a SequencedFragment object representing the entry. */ public class QseqInputFormat extends FileInputFormat<Text,SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.qseq-input.base-quality-encoding"; public static final String CONF_FILTER_FAILED_QC = "hbam.qseq-input.filter-failed-qc"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "illumina"; public static class QseqRecordReader extends RecordReader<Text,SequencedFragment> { /* * qseq format: * 11 tab-separated columns * * 1) Instrument * 2) Run id * 3) Lane number * 4) Tile number * 5) X pos * 6) Y pos * 7) Index sequence (0 for runs without multiplexing) * 8) Read Number * 9) Base Sequence * 10) Base Quality * 11) Filter: did the read pass filtering? 0 - No, 1 - Yes. */ // start: first valid data index private long start; // end: first index value beyond the slice, i.e. slice is in range [start,end) private long end; // pos: current position in file private long pos; // file: the file being read private Path file; private LineReader lineReader; private InputStream inputStream; private Text currentKey = new Text(); private SequencedFragment currentValue = new SequencedFragment(); private Text buffer = new Text(); private static final int NUM_QSEQ_COLS = 11; // for these, we have one per qseq field private int[] fieldPositions = new int[NUM_QSEQ_COLS]; private int[] fieldLengths = new int[NUM_QSEQ_COLS];
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/QseqInputFormat.java import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.CharacterCodingException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; // Copyright (C) 2011-2012 CRS4. // // This file is part of Hadoop-BAM. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package org.seqdoop.hadoop_bam; /** * Reads the Illumina qseq sequence format. * Key: instrument, run number, lane, tile, xpos, ypos, read number, delimited by ':' characters. * Value: a SequencedFragment object representing the entry. */ public class QseqInputFormat extends FileInputFormat<Text,SequencedFragment> { public static final String CONF_BASE_QUALITY_ENCODING = "hbam.qseq-input.base-quality-encoding"; public static final String CONF_FILTER_FAILED_QC = "hbam.qseq-input.filter-failed-qc"; public static final String CONF_BASE_QUALITY_ENCODING_DEFAULT = "illumina"; public static class QseqRecordReader extends RecordReader<Text,SequencedFragment> { /* * qseq format: * 11 tab-separated columns * * 1) Instrument * 2) Run id * 3) Lane number * 4) Tile number * 5) X pos * 6) Y pos * 7) Index sequence (0 for runs without multiplexing) * 8) Read Number * 9) Base Sequence * 10) Base Quality * 11) Filter: did the read pass filtering? 0 - No, 1 - Yes. */ // start: first valid data index private long start; // end: first index value beyond the slice, i.e. slice is in range [start,end) private long end; // pos: current position in file private long pos; // file: the file being read private Path file; private LineReader lineReader; private InputStream inputStream; private Text currentKey = new Text(); private SequencedFragment currentValue = new SequencedFragment(); private Text buffer = new Text(); private static final int NUM_QSEQ_COLS = 11; // for these, we have one per qseq field private int[] fieldPositions = new int[NUM_QSEQ_COLS]; private int[] fieldLengths = new int[NUM_QSEQ_COLS];
private BaseQualityEncoding qualityEncoding;
HadoopGenomics/Hadoop-BAM
src/main/java/org/seqdoop/hadoop_bam/QseqInputFormat.java
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // }
import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.CharacterCodingException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path;
// We use a temporary LineReader to read a partial line and find the // start of the first one on or after our starting position. // In case our slice starts right at the beginning of a line, we need to back // up by one position and then discard the first line. start -= 1; stream.seek(start); LineReader reader = new LineReader(stream); int bytesRead = reader.readLine(buffer, (int)Math.min(MAX_LINE_LENGTH, end - start)); start = start + bytesRead; stream.seek(start); } // else // if start == 0 we're starting at the beginning of a line pos = start; } protected void setConf(Configuration conf) { String encoding = conf.get(QseqInputFormat.CONF_BASE_QUALITY_ENCODING, conf.get(FormatConstants.CONF_INPUT_BASE_QUALITY_ENCODING, CONF_BASE_QUALITY_ENCODING_DEFAULT)); if ("illumina".equals(encoding)) qualityEncoding = BaseQualityEncoding.Illumina; else if ("sanger".equals(encoding)) qualityEncoding = BaseQualityEncoding.Sanger; else throw new RuntimeException("Unknown input base quality encoding value " + encoding);
// Path: src/main/java/org/seqdoop/hadoop_bam/FormatConstants.java // public enum BaseQualityEncoding { Illumina, Sanger }; // // Path: src/main/java/org/seqdoop/hadoop_bam/util/ConfHelper.java // public class ConfHelper // { // /** // * Convert a string to a boolean. // * // * Accepted values: "yes", "true", "t", "y", "1" // * "no", "false", "f", "n", "0" // * All comparisons are case insensitive. // * // * If the value provided is null, defaultValue is returned. // * // * @exception IllegalArgumentException Thrown if value is not // * null and doesn't match any of the accepted strings. // */ // public static boolean parseBoolean(String value, boolean defaultValue) // { // if (value == null) // return defaultValue; // // value = value.trim(); // // // any of the following will // final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; // final String[] acceptedFalse = new String[]{ "no", "false", "f", "n", "0" }; // // for (String possible: acceptedTrue) // { // if (possible.equalsIgnoreCase(value)) // return true; // } // for (String possible: acceptedFalse) // { // if (possible.equalsIgnoreCase(value)) // return false; // } // // throw new IllegalArgumentException("Unrecognized boolean value '" + value + "'"); // } // // public static boolean parseBoolean(Configuration conf, String propertyName, boolean defaultValue) // { // return parseBoolean(conf.get(propertyName), defaultValue); // } // } // Path: src/main/java/org/seqdoop/hadoop_bam/QseqInputFormat.java import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.seqdoop.hadoop_bam.FormatConstants.BaseQualityEncoding; import org.seqdoop.hadoop_bam.util.ConfHelper; import java.io.IOException; import java.io.InputStream; import java.nio.charset.CharacterCodingException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; // We use a temporary LineReader to read a partial line and find the // start of the first one on or after our starting position. // In case our slice starts right at the beginning of a line, we need to back // up by one position and then discard the first line. start -= 1; stream.seek(start); LineReader reader = new LineReader(stream); int bytesRead = reader.readLine(buffer, (int)Math.min(MAX_LINE_LENGTH, end - start)); start = start + bytesRead; stream.seek(start); } // else // if start == 0 we're starting at the beginning of a line pos = start; } protected void setConf(Configuration conf) { String encoding = conf.get(QseqInputFormat.CONF_BASE_QUALITY_ENCODING, conf.get(FormatConstants.CONF_INPUT_BASE_QUALITY_ENCODING, CONF_BASE_QUALITY_ENCODING_DEFAULT)); if ("illumina".equals(encoding)) qualityEncoding = BaseQualityEncoding.Illumina; else if ("sanger".equals(encoding)) qualityEncoding = BaseQualityEncoding.Sanger; else throw new RuntimeException("Unknown input base quality encoding value " + encoding);
filterFailedQC = ConfHelper.parseBoolean(
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock
ScriptRepo scriptRepo;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock ScriptRepo scriptRepo;
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock ScriptRepo scriptRepo;
private DataProviderService service;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock ScriptRepo scriptRepo; private DataProviderService service; @Before public void setUp() { MockitoAnnotations.initMocks(this); service = new DataProviderService(scriptRepo); } @Test public void itShouldSaveTheScript() { service.saveScript("The Script"); verify(scriptRepo, times(1)).save(
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderServiceTest.java import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class DataProviderServiceTest { @Mock ScriptRepo scriptRepo; private DataProviderService service; @Before public void setUp() { MockitoAnnotations.initMocks(this); service = new DataProviderService(scriptRepo); } @Test public void itShouldSaveTheScript() { service.saveScript("The Script"); verify(scriptRepo, times(1)).save(
argThat(new ArgumentMatcher<SanitizationScript>() {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // }
import java.util.List; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource;
package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") public interface BrokerActionRepository extends
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java import java.util.List; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") public interface BrokerActionRepository extends
PagingAndSortingRepository<BrokerAction, String> {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // }
import java.util.List; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource;
package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") public interface BrokerActionRepository extends PagingAndSortingRepository<BrokerAction, String> {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java import java.util.List; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") public interface BrokerActionRepository extends PagingAndSortingRepository<BrokerAction, String> {
List<BrokerAction> findByState(@Param("state") BrokerActionState state);
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/ServiceInstanceEntity.java // @Entity // public class ServiceInstanceEntity { // // @Id // private String id; // // private String copyId; // // private String spaceGuid; // // private String serviceInstanceId; // // private String planGuid; // // private String orgGuid; // // private String dashboardUrl; // // private String serviceDefinitionId; // // private String lastOperationState; // // private String lastOperationDescription; // // public ServiceInstanceEntity() { // } // // public ServiceInstanceEntity(ServiceInstance instance, String copyId) { // this.setCopyId(copyId); // this.setDashboardUrl(instance.getDashboardUrl()); // this.setOrgGuid(instance.getOrganizationGuid()); // this.setPlanGuid(instance.getPlanId()); // this.setServiceDefinitionId(instance.getServiceDefinitionId()); // this.setServiceInstanceId(instance.getServiceInstanceId()); // this.setId(instance.getServiceInstanceId()); // this.setSpaceGuid(instance.getSpaceGuid()); // this.setLastOperationDescription(instance // .getServiceInstanceLastOperation().getDescription()); // this.setLastOperationState(instance.getServiceInstanceLastOperation() // .getState()); // } // // public String getCopyId() { // return copyId; // } // // private void setCopyId(String copyId) { // this.copyId = copyId; // } // // public String getSpaceGuid() { // return spaceGuid; // } // // private void setSpaceGuid(String spaceGuid) { // this.spaceGuid = spaceGuid; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getPlanGuid() { // return planGuid; // } // // private void setPlanGuid(String planGuid) { // this.planGuid = planGuid; // } // // public String getOrgGuid() { // return orgGuid; // } // // private void setOrgGuid(String orgGuid) { // this.orgGuid = orgGuid; // } // // public String getDashboardUrl() { // return dashboardUrl; // } // // private void setDashboardUrl(String dashboardUrl) { // this.dashboardUrl = dashboardUrl; // } // // public String getServiceDefinitionId() { // return serviceDefinitionId; // } // // private void setServiceDefinitionId(String serviceDefinitionId) { // this.serviceDefinitionId = serviceDefinitionId; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // // public String getLastOperationState() { // return lastOperationState; // } // // private void setLastOperationState(String lastOperationState) { // this.lastOperationState = lastOperationState; // } // // public String getLastOperationDescription() { // return lastOperationDescription; // } // // private void setLastOperationDescription(String lastOperationDescription) { // this.lastOperationDescription = lastOperationDescription; // } // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.ServiceInstanceEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest; import org.cloudfoundry.community.servicebroker.model.OperationState; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceLastOperation;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceManager { private ServiceInstanceRepo repo; public LCServiceInstanceManager(ServiceInstanceRepo repo) { this.repo = repo; } public ServiceInstance getInstance(String id) {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/ServiceInstanceEntity.java // @Entity // public class ServiceInstanceEntity { // // @Id // private String id; // // private String copyId; // // private String spaceGuid; // // private String serviceInstanceId; // // private String planGuid; // // private String orgGuid; // // private String dashboardUrl; // // private String serviceDefinitionId; // // private String lastOperationState; // // private String lastOperationDescription; // // public ServiceInstanceEntity() { // } // // public ServiceInstanceEntity(ServiceInstance instance, String copyId) { // this.setCopyId(copyId); // this.setDashboardUrl(instance.getDashboardUrl()); // this.setOrgGuid(instance.getOrganizationGuid()); // this.setPlanGuid(instance.getPlanId()); // this.setServiceDefinitionId(instance.getServiceDefinitionId()); // this.setServiceInstanceId(instance.getServiceInstanceId()); // this.setId(instance.getServiceInstanceId()); // this.setSpaceGuid(instance.getSpaceGuid()); // this.setLastOperationDescription(instance // .getServiceInstanceLastOperation().getDescription()); // this.setLastOperationState(instance.getServiceInstanceLastOperation() // .getState()); // } // // public String getCopyId() { // return copyId; // } // // private void setCopyId(String copyId) { // this.copyId = copyId; // } // // public String getSpaceGuid() { // return spaceGuid; // } // // private void setSpaceGuid(String spaceGuid) { // this.spaceGuid = spaceGuid; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getPlanGuid() { // return planGuid; // } // // private void setPlanGuid(String planGuid) { // this.planGuid = planGuid; // } // // public String getOrgGuid() { // return orgGuid; // } // // private void setOrgGuid(String orgGuid) { // this.orgGuid = orgGuid; // } // // public String getDashboardUrl() { // return dashboardUrl; // } // // private void setDashboardUrl(String dashboardUrl) { // this.dashboardUrl = dashboardUrl; // } // // public String getServiceDefinitionId() { // return serviceDefinitionId; // } // // private void setServiceDefinitionId(String serviceDefinitionId) { // this.serviceDefinitionId = serviceDefinitionId; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // // public String getLastOperationState() { // return lastOperationState; // } // // private void setLastOperationState(String lastOperationState) { // this.lastOperationState = lastOperationState; // } // // public String getLastOperationDescription() { // return lastOperationDescription; // } // // private void setLastOperationDescription(String lastOperationDescription) { // this.lastOperationDescription = lastOperationDescription; // } // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.ServiceInstanceEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest; import org.cloudfoundry.community.servicebroker.model.OperationState; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceLastOperation; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceManager { private ServiceInstanceRepo repo; public LCServiceInstanceManager(ServiceInstanceRepo repo) { this.repo = repo; } public ServiceInstance getInstance(String id) {
ServiceInstanceEntity entity = repo.findOne(id);
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingService.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java // @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") // public interface BrokerActionRepository extends // PagingAndSortingRepository<BrokerAction, String> { // // List<BrokerAction> findByState(@Param("state") BrokerActionState state); // }
import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.COMPLETE; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.FAILED; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.IN_PROGRESS; import java.util.List; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BrokerActionRepository; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException; import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceBindingExistsException; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class LCServiceInstanceBindingService implements ServiceInstanceBindingService {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java // @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") // public interface BrokerActionRepository extends // PagingAndSortingRepository<BrokerAction, String> { // // List<BrokerAction> findByState(@Param("state") BrokerActionState state); // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingService.java import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.COMPLETE; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.FAILED; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.IN_PROGRESS; import java.util.List; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BrokerActionRepository; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException; import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceBindingExistsException; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class LCServiceInstanceBindingService implements ServiceInstanceBindingService {
private CopyProvider provider;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingService.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java // @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") // public interface BrokerActionRepository extends // PagingAndSortingRepository<BrokerAction, String> { // // List<BrokerAction> findByState(@Param("state") BrokerActionState state); // }
import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.COMPLETE; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.FAILED; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.IN_PROGRESS; import java.util.List; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BrokerActionRepository; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException; import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceBindingExistsException; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class LCServiceInstanceBindingService implements ServiceInstanceBindingService { private CopyProvider provider; private Logger logger = Logger .getLogger(LCServiceInstanceBindingService.class); private LCServiceInstanceBindingManager bindings; private LCServiceInstanceService instanceService;
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerAction.java // @Entity // public class BrokerAction { // // @Id // private String id; // // private String actor; // // private BrokerActionState state; // // private String action; // // public BrokerAction() { // } // // public BrokerAction(String id, BrokerActionState state, String action) { // this.setId(id); // this.actor = id; // this.state = state; // this.action = action; // } // // public String getActor() { // return actor; // } // // public void setActor(String actor) { // this.actor = actor; // } // // public BrokerActionState getState() { // return state; // } // // public void setState(BrokerActionState state) { // this.state = state; // } // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BrokerActionState.java // public enum BrokerActionState { // FAILED, COMPLETE, IN_PROGRESS // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BrokerActionRepository.java // @RepositoryRestResource(collectionResourceRel = "actions", path = "actions") // public interface BrokerActionRepository extends // PagingAndSortingRepository<BrokerAction, String> { // // List<BrokerAction> findByState(@Param("state") BrokerActionState state); // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingService.java import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.COMPLETE; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.FAILED; import static org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState.IN_PROGRESS; import java.util.List; import java.util.stream.Collectors; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerAction; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BrokerActionState; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BrokerActionRepository; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException; import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceBindingExistsException; import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.DeleteServiceInstanceBindingRequest; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.cloudfoundry.community.servicebroker.service.ServiceInstanceBindingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class LCServiceInstanceBindingService implements ServiceInstanceBindingService { private CopyProvider provider; private Logger logger = Logger .getLogger(LCServiceInstanceBindingService.class); private LCServiceInstanceBindingManager bindings; private LCServiceInstanceService instanceService;
private BrokerActionRepository brokerRepo;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/servicebinding/BrokerIntegrationTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // public static String COPY = "copy"; // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/DataLifecycleServiceBrokerApplication.java // @SpringBootApplication // public class DataLifecycleServiceBrokerApplication { // // public static void main(String[] args) { // SpringApplication // .run(DataLifecycleServiceBrokerApplication.class, args); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // }
import static com.jayway.restassured.RestAssured.given; import static org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig.COPY; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import java.sql.SQLException; import java.util.Date; import net.minidev.json.JSONObject; import org.apache.http.entity.ContentType; import org.cloudfoundry.community.servicebroker.datalifecycle.DataLifecycleServiceBrokerApplication; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.util.json.JSONException; import com.jayway.restassured.RestAssured; import com.jayway.restassured.builder.RequestSpecBuilder; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification;
package org.cloudfoundry.community.servicebroker.datalifecycle.servicebinding; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = DataLifecycleServiceBrokerApplication.class) @WebAppConfiguration @IntegrationTest("server.port:0") @Category(IntegrationTest.class) /** * These tests assume an empty VPC with one instance (the prod one) running. * You can set env variables to effect where and how the ec2Client behaves, * see README.md in the project root * */ public class BrokerIntegrationTest { // TODO DRY w/ Catalog test @Value("${local.server.port}") private int port; @Value("#{environment.SECURITY_USER_NAME}") private String username; @Value("#{environment.SECURITY_USER_PASSWORD}") private String password; @Autowired private AmazonEC2Client ec2Client; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstanceId; @Autowired
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // public static String COPY = "copy"; // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/DataLifecycleServiceBrokerApplication.java // @SpringBootApplication // public class DataLifecycleServiceBrokerApplication { // // public static void main(String[] args) { // SpringApplication // .run(DataLifecycleServiceBrokerApplication.class, args); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/servicebinding/BrokerIntegrationTest.java import static com.jayway.restassured.RestAssured.given; import static org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig.COPY; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import java.sql.SQLException; import java.util.Date; import net.minidev.json.JSONObject; import org.apache.http.entity.ContentType; import org.cloudfoundry.community.servicebroker.datalifecycle.DataLifecycleServiceBrokerApplication; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.util.json.JSONException; import com.jayway.restassured.RestAssured; import com.jayway.restassured.builder.RequestSpecBuilder; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; package org.cloudfoundry.community.servicebroker.datalifecycle.servicebinding; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = DataLifecycleServiceBrokerApplication.class) @WebAppConfiguration @IntegrationTest("server.port:0") @Category(IntegrationTest.class) /** * These tests assume an empty VPC with one instance (the prod one) running. * You can set env variables to effect where and how the ec2Client behaves, * see README.md in the project root * */ public class BrokerIntegrationTest { // TODO DRY w/ Catalog test @Value("${local.server.port}") private int port; @Value("#{environment.SECURITY_USER_NAME}") private String username; @Value("#{environment.SECURITY_USER_PASSWORD}") private String password; @Autowired private AmazonEC2Client ec2Client; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstanceId; @Autowired
private BindingRepository bindingRepo;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/servicebinding/BrokerIntegrationTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // public static String COPY = "copy"; // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/DataLifecycleServiceBrokerApplication.java // @SpringBootApplication // public class DataLifecycleServiceBrokerApplication { // // public static void main(String[] args) { // SpringApplication // .run(DataLifecycleServiceBrokerApplication.class, args); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // }
import static com.jayway.restassured.RestAssured.given; import static org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig.COPY; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import java.sql.SQLException; import java.util.Date; import net.minidev.json.JSONObject; import org.apache.http.entity.ContentType; import org.cloudfoundry.community.servicebroker.datalifecycle.DataLifecycleServiceBrokerApplication; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.util.json.JSONException; import com.jayway.restassured.RestAssured; import com.jayway.restassured.builder.RequestSpecBuilder; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification;
givenTheBroker() .delete("/v2/service_instances/1234?service_id=lifecycle-sb&plan_id=copy&accepts_incomplete=true") .then().statusCode(410); validateNothingProvisioned(); deleteScript(); } private void unprovisionAndUnbindCopy() throws Exception { givenTheBroker() .delete("/v2/service_instances/1234/service_bindings/1234521?service_id=lifecycle-sb&plan_id=copy") .then().statusCode(200); validateNoBinding(); givenTheBroker() .delete("/v2/service_instances/1234?service_id=lifecycle-sb&plan_id=copy&accepts_incomplete=true") .then().statusCode(202); validateNothingProvisioned(); } private void provisionAndBindCopy() throws Exception { validateNoBinding(); validateNothingProvisioned(); uploadScript(); JSONObject serviceInstance = new JSONObject(); serviceInstance.put("service_id", "lifecycle-sb");
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // public static String COPY = "copy"; // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/DataLifecycleServiceBrokerApplication.java // @SpringBootApplication // public class DataLifecycleServiceBrokerApplication { // // public static void main(String[] args) { // SpringApplication // .run(DataLifecycleServiceBrokerApplication.class, args); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/servicebinding/BrokerIntegrationTest.java import static com.jayway.restassured.RestAssured.given; import static org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig.COPY; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import java.sql.SQLException; import java.util.Date; import net.minidev.json.JSONObject; import org.apache.http.entity.ContentType; import org.cloudfoundry.community.servicebroker.datalifecycle.DataLifecycleServiceBrokerApplication; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstance; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.util.json.JSONException; import com.jayway.restassured.RestAssured; import com.jayway.restassured.builder.RequestSpecBuilder; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; givenTheBroker() .delete("/v2/service_instances/1234?service_id=lifecycle-sb&plan_id=copy&accepts_incomplete=true") .then().statusCode(410); validateNothingProvisioned(); deleteScript(); } private void unprovisionAndUnbindCopy() throws Exception { givenTheBroker() .delete("/v2/service_instances/1234/service_bindings/1234521?service_id=lifecycle-sb&plan_id=copy") .then().statusCode(200); validateNoBinding(); givenTheBroker() .delete("/v2/service_instances/1234?service_id=lifecycle-sb&plan_id=copy&accepts_incomplete=true") .then().statusCode(202); validateNothingProvisioned(); } private void provisionAndBindCopy() throws Exception { validateNoBinding(); validateNothingProvisioned(); uploadScript(); JSONObject serviceInstance = new JSONObject(); serviceInstance.put("service_id", "lifecycle-sb");
serviceInstance.put("plan_id", COPY);
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource;
package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") public interface BindingRepository extends
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; package org.cloudfoundry.community.servicebroker.datalifecycle.repo; @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") public interface BindingRepository extends
PagingAndSortingRepository<BindingEntity, String> {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.Map;
package org.cloudfoundry.community.servicebroker.datalifecycle.controller; @RestController class SanitizeController { @Autowired
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.Map; package org.cloudfoundry.community.servicebroker.datalifecycle.controller; @RestController class SanitizeController { @Autowired
private DataProviderService dataService;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCServiceInstanceManagerConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java // public class LCServiceInstanceManager { // private ServiceInstanceRepo repo; // // public LCServiceInstanceManager(ServiceInstanceRepo repo) { // this.repo = repo; // } // // public ServiceInstance getInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return convert(entity); // } // // public String getCopyIdForInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return null == entity ? null : entity.getCopyId(); // } // // // TODO this could have a more natural data structure. // public Collection<Pair<String, ServiceInstance>> getInstances() { // List<Pair<String, ServiceInstance>> instancePairs = new ArrayList<Pair<String, ServiceInstance>>(); // repo.findAll().forEach( // e -> instancePairs // .add(new ImmutablePair<String, ServiceInstance>(e // .getCopyId(), convert(e)))); // return instancePairs; // } // // public void saveInstance(ServiceInstance instance, String copyId) { // repo.save(new ServiceInstanceEntity(instance, copyId)); // } // // public ServiceInstance removeInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // if (null != entity) { // repo.delete(id); // } // return convert(entity); // } // // private ServiceInstance convert(ServiceInstanceEntity i) { // if (null == i) { // return null; // } // // TODO Gross, the base should handle this for us. // OperationState state = null; // switch (i.getLastOperationState()) { // case "in progress": // state = OperationState.IN_PROGRESS; // break; // case "succeeded": // state = OperationState.SUCCEEDED; // break; // case "failed": // state = OperationState.FAILED; // break; // default: // assert (false); // } // // @formatter:off // return new ServiceInstance(new CreateServiceInstanceRequest( // i.getServiceDefinitionId(), i.getPlanGuid(), i.getOrgGuid(), // i.getSpaceGuid(), true).withServiceInstanceId(i // .getServiceInstanceId())) // .withDashboardUrl(i.getDashboardUrl()) // .and() // .withLastOperation( // new ServiceInstanceLastOperation(i // .getLastOperationDescription(), state)); // // @formatter:on // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class LCServiceInstanceManagerConfig { @Autowired private
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java // public class LCServiceInstanceManager { // private ServiceInstanceRepo repo; // // public LCServiceInstanceManager(ServiceInstanceRepo repo) { // this.repo = repo; // } // // public ServiceInstance getInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return convert(entity); // } // // public String getCopyIdForInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return null == entity ? null : entity.getCopyId(); // } // // // TODO this could have a more natural data structure. // public Collection<Pair<String, ServiceInstance>> getInstances() { // List<Pair<String, ServiceInstance>> instancePairs = new ArrayList<Pair<String, ServiceInstance>>(); // repo.findAll().forEach( // e -> instancePairs // .add(new ImmutablePair<String, ServiceInstance>(e // .getCopyId(), convert(e)))); // return instancePairs; // } // // public void saveInstance(ServiceInstance instance, String copyId) { // repo.save(new ServiceInstanceEntity(instance, copyId)); // } // // public ServiceInstance removeInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // if (null != entity) { // repo.delete(id); // } // return convert(entity); // } // // private ServiceInstance convert(ServiceInstanceEntity i) { // if (null == i) { // return null; // } // // TODO Gross, the base should handle this for us. // OperationState state = null; // switch (i.getLastOperationState()) { // case "in progress": // state = OperationState.IN_PROGRESS; // break; // case "succeeded": // state = OperationState.SUCCEEDED; // break; // case "failed": // state = OperationState.FAILED; // break; // default: // assert (false); // } // // @formatter:off // return new ServiceInstance(new CreateServiceInstanceRequest( // i.getServiceDefinitionId(), i.getPlanGuid(), i.getOrgGuid(), // i.getSpaceGuid(), true).withServiceInstanceId(i // .getServiceInstanceId())) // .withDashboardUrl(i.getDashboardUrl()) // .and() // .withLastOperation( // new ServiceInstanceLastOperation(i // .getLastOperationDescription(), state)); // // @formatter:on // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCServiceInstanceManagerConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class LCServiceInstanceManagerConfig { @Autowired private
ServiceInstanceRepo repo;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCServiceInstanceManagerConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java // public class LCServiceInstanceManager { // private ServiceInstanceRepo repo; // // public LCServiceInstanceManager(ServiceInstanceRepo repo) { // this.repo = repo; // } // // public ServiceInstance getInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return convert(entity); // } // // public String getCopyIdForInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return null == entity ? null : entity.getCopyId(); // } // // // TODO this could have a more natural data structure. // public Collection<Pair<String, ServiceInstance>> getInstances() { // List<Pair<String, ServiceInstance>> instancePairs = new ArrayList<Pair<String, ServiceInstance>>(); // repo.findAll().forEach( // e -> instancePairs // .add(new ImmutablePair<String, ServiceInstance>(e // .getCopyId(), convert(e)))); // return instancePairs; // } // // public void saveInstance(ServiceInstance instance, String copyId) { // repo.save(new ServiceInstanceEntity(instance, copyId)); // } // // public ServiceInstance removeInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // if (null != entity) { // repo.delete(id); // } // return convert(entity); // } // // private ServiceInstance convert(ServiceInstanceEntity i) { // if (null == i) { // return null; // } // // TODO Gross, the base should handle this for us. // OperationState state = null; // switch (i.getLastOperationState()) { // case "in progress": // state = OperationState.IN_PROGRESS; // break; // case "succeeded": // state = OperationState.SUCCEEDED; // break; // case "failed": // state = OperationState.FAILED; // break; // default: // assert (false); // } // // @formatter:off // return new ServiceInstance(new CreateServiceInstanceRequest( // i.getServiceDefinitionId(), i.getPlanGuid(), i.getOrgGuid(), // i.getSpaceGuid(), true).withServiceInstanceId(i // .getServiceInstanceId())) // .withDashboardUrl(i.getDashboardUrl()) // .and() // .withLastOperation( // new ServiceInstanceLastOperation(i // .getLastOperationDescription(), state)); // // @formatter:on // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class LCServiceInstanceManagerConfig { @Autowired private ServiceInstanceRepo repo; @Bean
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ServiceInstanceRepo.java // public interface ServiceInstanceRepo extends // PagingAndSortingRepository<ServiceInstanceEntity, String> { // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceManager.java // public class LCServiceInstanceManager { // private ServiceInstanceRepo repo; // // public LCServiceInstanceManager(ServiceInstanceRepo repo) { // this.repo = repo; // } // // public ServiceInstance getInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return convert(entity); // } // // public String getCopyIdForInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // return null == entity ? null : entity.getCopyId(); // } // // // TODO this could have a more natural data structure. // public Collection<Pair<String, ServiceInstance>> getInstances() { // List<Pair<String, ServiceInstance>> instancePairs = new ArrayList<Pair<String, ServiceInstance>>(); // repo.findAll().forEach( // e -> instancePairs // .add(new ImmutablePair<String, ServiceInstance>(e // .getCopyId(), convert(e)))); // return instancePairs; // } // // public void saveInstance(ServiceInstance instance, String copyId) { // repo.save(new ServiceInstanceEntity(instance, copyId)); // } // // public ServiceInstance removeInstance(String id) { // ServiceInstanceEntity entity = repo.findOne(id); // if (null != entity) { // repo.delete(id); // } // return convert(entity); // } // // private ServiceInstance convert(ServiceInstanceEntity i) { // if (null == i) { // return null; // } // // TODO Gross, the base should handle this for us. // OperationState state = null; // switch (i.getLastOperationState()) { // case "in progress": // state = OperationState.IN_PROGRESS; // break; // case "succeeded": // state = OperationState.SUCCEEDED; // break; // case "failed": // state = OperationState.FAILED; // break; // default: // assert (false); // } // // @formatter:off // return new ServiceInstance(new CreateServiceInstanceRequest( // i.getServiceDefinitionId(), i.getPlanGuid(), i.getOrgGuid(), // i.getSpaceGuid(), true).withServiceInstanceId(i // .getServiceInstanceId())) // .withDashboardUrl(i.getDashboardUrl()) // .and() // .withLastOperation( // new ServiceInstanceLastOperation(i // .getLastOperationDescription(), state)); // // @formatter:on // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCServiceInstanceManagerConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ServiceInstanceRepo; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class LCServiceInstanceManagerConfig { @Autowired private ServiceInstanceRepo repo; @Bean
LCServiceInstanceManager newLCServiceInstanceManager() {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // }
import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class DataProviderService {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class DataProviderService {
private ScriptRepo scriptRepo;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // }
import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class DataProviderService { private ScriptRepo scriptRepo; @Autowired public DataProviderService(ScriptRepo scriptRepo) { this.scriptRepo = scriptRepo; } public void saveScript(String script) {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/SanitizationScript.java // @Entity // public class SanitizationScript { // // public final static long ID = 1; // // @Id // private long id = ID; // // private String script; // // protected SanitizationScript() { // } // // public SanitizationScript(final String script) { // this.setScript(script); // } // // public String getScript() { // return script; // } // // private void setScript(String script) { // this.script = script; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/ScriptRepo.java // public interface ScriptRepo extends CrudRepository<SanitizationScript, Long> { // // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java import org.cloudfoundry.community.servicebroker.datalifecycle.model.SanitizationScript; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.ScriptRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package org.cloudfoundry.community.servicebroker.datalifecycle.service; @Service public class DataProviderService { private ScriptRepo scriptRepo; @Autowired public DataProviderService(ScriptRepo scriptRepo) { this.scriptRepo = scriptRepo; } public void saveScript(String script) {
scriptRepo.save(new SanitizationScript(script));
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/BindingManagerConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class BindingManagerConfig { @Autowired
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/BindingManagerConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class BindingManagerConfig { @Autowired
private BindingRepository repo;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/BindingManagerConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class BindingManagerConfig { @Autowired private BindingRepository repo; @Bean
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/BindingManagerConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class BindingManagerConfig { @Autowired private BindingRepository repo; @Bean
public LCServiceInstanceBindingManager bindingRepo() {
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // @Configuration // public class LCCatalogConfig { // // private ServiceDefinition postgresServiceDefinition; // // public static String PRODUCTION = "prod"; // public static String COPY = "copy"; // // public LCCatalogConfig() { // List<Plan> plans = new ArrayList<Plan>(); // plans.add(new Plan(PRODUCTION, PRODUCTION, "The production datasource", // getProdMetadata())); // plans.add(new Plan(COPY, COPY, "Copy of production datasource", // getCopyMetadata())); // postgresServiceDefinition = new ServiceDefinition("lifecycle-sb", // "lifecycle-sb", "Postgres Running in AWS", true, plans); // postgresServiceDefinition.setPlanUpdatable(false); // } // // private Map<String, Object> getProdMetadata() { // return new HashMap<String, Object>(); // } // // private Map<String, Object> getCopyMetadata() { // return new HashMap<String, Object>(); // } // // @Bean // public Catalog catalog() { // return new Catalog(Collections.singletonList(postgresServiceDefinition)); // } // }
import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig; import org.cloudfoundry.community.servicebroker.model.Catalog; import org.junit.Before; import org.junit.Test;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; public class LCCatalogTest { private Catalog pgCat; @Before public void setUp() {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogConfig.java // @Configuration // public class LCCatalogConfig { // // private ServiceDefinition postgresServiceDefinition; // // public static String PRODUCTION = "prod"; // public static String COPY = "copy"; // // public LCCatalogConfig() { // List<Plan> plans = new ArrayList<Plan>(); // plans.add(new Plan(PRODUCTION, PRODUCTION, "The production datasource", // getProdMetadata())); // plans.add(new Plan(COPY, COPY, "Copy of production datasource", // getCopyMetadata())); // postgresServiceDefinition = new ServiceDefinition("lifecycle-sb", // "lifecycle-sb", "Postgres Running in AWS", true, plans); // postgresServiceDefinition.setPlanUpdatable(false); // } // // private Map<String, Object> getProdMetadata() { // return new HashMap<String, Object>(); // } // // private Map<String, Object> getCopyMetadata() { // return new HashMap<String, Object>(); // } // // @Bean // public Catalog catalog() { // return new Catalog(Collections.singletonList(postgresServiceDefinition)); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/LCCatalogTest.java import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import org.cloudfoundry.community.servicebroker.datalifecycle.config.LCCatalogConfig; import org.cloudfoundry.community.servicebroker.model.Catalog; import org.junit.Before; import org.junit.Test; package org.cloudfoundry.community.servicebroker.datalifecycle.config; public class LCCatalogTest { private Catalog pgCat; @Before public void setUp() {
pgCat = new LCCatalogConfig().catalog();
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/DataProvider.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/exception/DataProviderSanitizationFailedException.java // public class DataProviderSanitizationFailedException extends Exception { // // private static final long serialVersionUID = 1L; // // public DataProviderSanitizationFailedException(String msg) { // super(msg); // } // }
import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.exception.DataProviderSanitizationFailedException;
package org.cloudfoundry.community.servicebroker.datalifecycle.provider; public interface DataProvider { /** * Sanitize the data source with the incoming script. This method is called * upon provision and typically removes or modifies sensitive data from the * database. This method is always called in order to ensure the sanitize * point has a chance to perform operations which my not be scripted. * * Creds are obtained from the CopyProvider after creating a copy, so the * DataProvider needs to understand the object, as it's opaque to the * framework. * * @param script * to run against the data source, may be null * @param creds * to login to service instance, provided by the CopyProvider * @throws DataProviderSanitizationFailedException * if the script fails. */ void sanitize(String script, Map<String, Object> creds)
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/exception/DataProviderSanitizationFailedException.java // public class DataProviderSanitizationFailedException extends Exception { // // private static final long serialVersionUID = 1L; // // public DataProviderSanitizationFailedException(String msg) { // super(msg); // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/DataProvider.java import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.exception.DataProviderSanitizationFailedException; package org.cloudfoundry.community.servicebroker.datalifecycle.provider; public interface DataProvider { /** * Sanitize the data source with the incoming script. This method is called * upon provision and typically removes or modifies sensitive data from the * database. This method is always called in order to ensure the sanitize * point has a chance to perform operations which my not be scripted. * * Creds are obtained from the CopyProvider after creating a copy, so the * DataProvider needs to understand the object, as it's opaque to the * framework. * * @param script * to run against the data source, may be null * @param creds * to login to service instance, provided by the CopyProvider * @throws DataProviderSanitizationFailedException * if the script fails. */ void sanitize(String script, Map<String, Object> creds)
throws DataProviderSanitizationFailedException;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeControllerTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java // @RestController // class SanitizeController { // // @Autowired // private DataProviderService dataService; // // private static final String location = "/api/sanitizescript"; // // @RequestMapping(value = location, method = RequestMethod.GET) // public ResponseEntity<JSONObject> getSanitizeScript() { // String script = dataService.getScript(); // JSONObject response = new JSONObject(); // if (null != script) { // // response.put("script", script); // } // return new ResponseEntity<JSONObject>(response, HttpStatus.OK); // } // // @RequestMapping(value = location, method = RequestMethod.POST, produces = "application/json") // public ResponseEntity<String> addSanitizeScript(@RequestBody Map<String, Object> script) { // // dataService.saveScript((String) script.get("script")); // String response = "{}"; // // HttpHeaders headers = new HttpHeaders(); // UriComponents components = UriComponentsBuilder.fromPath(location) // .buildAndExpand(); // // headers.setLocation(components.toUri()); // return new ResponseEntity<String>(response, headers, HttpStatus.CREATED); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.controller.SanitizeController; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
package org.cloudfoundry.community.servicebroker.datalifecycle.controller; public class SanitizeControllerTest { private MockMvc mockMvc; private String script = "drop * from table"; private String location = "/api/sanitizescript"; @InjectMocks
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java // @RestController // class SanitizeController { // // @Autowired // private DataProviderService dataService; // // private static final String location = "/api/sanitizescript"; // // @RequestMapping(value = location, method = RequestMethod.GET) // public ResponseEntity<JSONObject> getSanitizeScript() { // String script = dataService.getScript(); // JSONObject response = new JSONObject(); // if (null != script) { // // response.put("script", script); // } // return new ResponseEntity<JSONObject>(response, HttpStatus.OK); // } // // @RequestMapping(value = location, method = RequestMethod.POST, produces = "application/json") // public ResponseEntity<String> addSanitizeScript(@RequestBody Map<String, Object> script) { // // dataService.saveScript((String) script.get("script")); // String response = "{}"; // // HttpHeaders headers = new HttpHeaders(); // UriComponents components = UriComponentsBuilder.fromPath(location) // .buildAndExpand(); // // headers.setLocation(components.toUri()); // return new ResponseEntity<String>(response, headers, HttpStatus.CREATED); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeControllerTest.java import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.controller.SanitizeController; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; package org.cloudfoundry.community.servicebroker.datalifecycle.controller; public class SanitizeControllerTest { private MockMvc mockMvc; private String script = "drop * from table"; private String location = "/api/sanitizescript"; @InjectMocks
SanitizeController sanitizeController;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeControllerTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java // @RestController // class SanitizeController { // // @Autowired // private DataProviderService dataService; // // private static final String location = "/api/sanitizescript"; // // @RequestMapping(value = location, method = RequestMethod.GET) // public ResponseEntity<JSONObject> getSanitizeScript() { // String script = dataService.getScript(); // JSONObject response = new JSONObject(); // if (null != script) { // // response.put("script", script); // } // return new ResponseEntity<JSONObject>(response, HttpStatus.OK); // } // // @RequestMapping(value = location, method = RequestMethod.POST, produces = "application/json") // public ResponseEntity<String> addSanitizeScript(@RequestBody Map<String, Object> script) { // // dataService.saveScript((String) script.get("script")); // String response = "{}"; // // HttpHeaders headers = new HttpHeaders(); // UriComponents components = UriComponentsBuilder.fromPath(location) // .buildAndExpand(); // // headers.setLocation(components.toUri()); // return new ResponseEntity<String>(response, headers, HttpStatus.CREATED); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // }
import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.controller.SanitizeController; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
package org.cloudfoundry.community.servicebroker.datalifecycle.controller; public class SanitizeControllerTest { private MockMvc mockMvc; private String script = "drop * from table"; private String location = "/api/sanitizescript"; @InjectMocks SanitizeController sanitizeController; @Mock
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeController.java // @RestController // class SanitizeController { // // @Autowired // private DataProviderService dataService; // // private static final String location = "/api/sanitizescript"; // // @RequestMapping(value = location, method = RequestMethod.GET) // public ResponseEntity<JSONObject> getSanitizeScript() { // String script = dataService.getScript(); // JSONObject response = new JSONObject(); // if (null != script) { // // response.put("script", script); // } // return new ResponseEntity<JSONObject>(response, HttpStatus.OK); // } // // @RequestMapping(value = location, method = RequestMethod.POST, produces = "application/json") // public ResponseEntity<String> addSanitizeScript(@RequestBody Map<String, Object> script) { // // dataService.saveScript((String) script.get("script")); // String response = "{}"; // // HttpHeaders headers = new HttpHeaders(); // UriComponents components = UriComponentsBuilder.fromPath(location) // .buildAndExpand(); // // headers.setLocation(components.toUri()); // return new ResponseEntity<String>(response, headers, HttpStatus.CREATED); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/DataProviderService.java // @Service // public class DataProviderService { // // private ScriptRepo scriptRepo; // // @Autowired // public DataProviderService(ScriptRepo scriptRepo) { // this.scriptRepo = scriptRepo; // } // // public void saveScript(String script) { // scriptRepo.save(new SanitizationScript(script)); // } // // /** // * Retrieve the sanitization script from the repo // * // * @return the script if one has been set, null otherwise. // */ // public String getScript() { // SanitizationScript result = scriptRepo.findOne(SanitizationScript.ID); // // return result == null ? null : result.getScript(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/controller/SanitizeControllerTest.java import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import net.minidev.json.JSONObject; import org.cloudfoundry.community.servicebroker.datalifecycle.controller.SanitizeController; import org.cloudfoundry.community.servicebroker.datalifecycle.service.DataProviderService; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; package org.cloudfoundry.community.servicebroker.datalifecycle.controller; public class SanitizeControllerTest { private MockMvc mockMvc; private String script = "drop * from table"; private String location = "/api/sanitizescript"; @InjectMocks SanitizeController sanitizeController; @Mock
DataProviderService service;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePairTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // }
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.junit.Test;
package org.cloudfoundry.community.servicebroker.datalifecycle.dto; public class InstancePairTest { @Test public void theyAreEqual() {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePair.java // public class InstancePair { // // private String sourceInstance; // private String copyInstance; // // public InstancePair(String sourceInstance, String copyInstance) { // this.sourceInstance = sourceInstance; // this.copyInstance = copyInstance; // } // // public String getSource() { // return sourceInstance; // } // // public String getCopy() { // return copyInstance; // } // // @Override // public boolean equals(Object lhs) { // return lhs instanceof InstancePair && this.hashCode() == lhs.hashCode(); // } // // @Override // public int hashCode() { // return sourceInstance.hashCode() + copyInstance.hashCode(); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/dto/InstancePairTest.java import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import org.cloudfoundry.community.servicebroker.datalifecycle.dto.InstancePair; import org.junit.Test; package org.cloudfoundry.community.servicebroker.datalifecycle.dto; public class InstancePairTest { @Test public void theyAreEqual() {
assertThat(new InstancePair("source", "copy"),
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // }
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock
BindingRepository repo;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // }
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock BindingRepository repo;
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock BindingRepository repo;
private LCServiceInstanceBindingManager bindingManager;
krujos/data-lifecycle-service-broker
src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // }
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock BindingRepository repo; private LCServiceInstanceBindingManager bindingManager; private Map<String, Object> creds = new HashMap<String, Object>(); private ServiceInstanceBinding binding = new ServiceInstanceBinding("binding-id", "service-instance-id", creds, "syslog-drain", "app-guid");
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java // public class LCServiceInstanceBindingManager { // // @Autowired // private BindingRepository repo; // // public LCServiceInstanceBindingManager(BindingRepository repo) { // this.repo = repo; // } // // public Collection<ServiceInstanceBinding> getBindings() { // Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); // repo.findAll().forEach(t -> bindings.add(convert(t))); // return bindings; // } // // public ServiceInstanceBinding getBinding(String bindingId) { // return convert(repo.findOne(bindingId)); // } // // public ServiceInstanceBinding removeBinding(String bindingId) { // BindingEntity binding = repo.findOne(bindingId); // if (null != binding) { // repo.delete(bindingId); // } // return convert(binding); // } // // public void saveBinding(ServiceInstanceBinding binding) { // repo.save(new BindingEntity(binding)); // } // // private ServiceInstanceBinding convert(BindingEntity binding) { // return null == binding ? null : new ServiceInstanceBinding( // binding.getBindingId(), binding.getServiceInstanceId(), null, // binding.getDrainUrl(), binding.getAppGuid()); // } // } // Path: src/test/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/ServiceInstanceBindingManagerTest.java import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.datalifecycle.service.LCServiceInstanceBindingManager; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class ServiceInstanceBindingManagerTest { @Mock BindingRepository repo; private LCServiceInstanceBindingManager bindingManager; private Map<String, Object> creds = new HashMap<String, Object>(); private ServiceInstanceBinding binding = new ServiceInstanceBinding("binding-id", "service-instance-id", creds, "syslog-drain", "app-guid");
private BindingEntity bindingEntity = new BindingEntity(binding);
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/HostUtilsConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration public class HostUtilsConfig { @Bean
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/HostUtilsConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration public class HostUtilsConfig { @Bean
public HostUtils newHostUtils() {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/postgres/PostgresDataProvider.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/exception/DataProviderSanitizationFailedException.java // public class DataProviderSanitizationFailedException extends Exception { // // private static final long serialVersionUID = 1L; // // public DataProviderSanitizationFailedException(String msg) { // super(msg); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/DataProvider.java // public interface DataProvider { // // /** // * Sanitize the data source with the incoming script. This method is called // * upon provision and typically removes or modifies sensitive data from the // * database. This method is always called in order to ensure the sanitize // * point has a chance to perform operations which my not be scripted. // * // * Creds are obtained from the CopyProvider after creating a copy, so the // * DataProvider needs to understand the object, as it's opaque to the // * framework. // * // * @param script // * to run against the data source, may be null // * @param creds // * to login to service instance, provided by the CopyProvider // * @throws DataProviderSanitizationFailedException // * if the script fails. // */ // void sanitize(String script, Map<String, Object> creds) // throws DataProviderSanitizationFailedException; // // //TODO Password change is implicit in above, explicit api? // }
import java.sql.SQLException; import java.util.Map; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.exception.DataProviderSanitizationFailedException; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.DataProvider;
package org.cloudfoundry.community.servicebroker.datalifecycle.postgres; /** * Created by jkruck on 4/20/15. */ public class PostgresDataProvider implements DataProvider { private Logger log = Logger.getLogger(PostgresDataProvider.class); private PostgresScriptExecutor executor; public PostgresDataProvider(PostgresScriptExecutor executor) { this.executor = executor; } @Override public void sanitize(String script, Map<String, Object> creds)
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/exception/DataProviderSanitizationFailedException.java // public class DataProviderSanitizationFailedException extends Exception { // // private static final long serialVersionUID = 1L; // // public DataProviderSanitizationFailedException(String msg) { // super(msg); // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/DataProvider.java // public interface DataProvider { // // /** // * Sanitize the data source with the incoming script. This method is called // * upon provision and typically removes or modifies sensitive data from the // * database. This method is always called in order to ensure the sanitize // * point has a chance to perform operations which my not be scripted. // * // * Creds are obtained from the CopyProvider after creating a copy, so the // * DataProvider needs to understand the object, as it's opaque to the // * framework. // * // * @param script // * to run against the data source, may be null // * @param creds // * to login to service instance, provided by the CopyProvider // * @throws DataProviderSanitizationFailedException // * if the script fails. // */ // void sanitize(String script, Map<String, Object> creds) // throws DataProviderSanitizationFailedException; // // //TODO Password change is implicit in above, explicit api? // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/postgres/PostgresDataProvider.java import java.sql.SQLException; import java.util.Map; import org.apache.log4j.Logger; import org.cloudfoundry.community.servicebroker.datalifecycle.exception.DataProviderSanitizationFailedException; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.DataProvider; package org.cloudfoundry.community.servicebroker.datalifecycle.postgres; /** * Created by jkruck on 4/20/15. */ public class PostgresDataProvider implements DataProvider { private Logger log = Logger.getLogger(PostgresDataProvider.class); private PostgresScriptExecutor executor; public PostgresDataProvider(PostgresScriptExecutor executor) { this.executor = executor; } @Override public void sanitize(String script, Map<String, Object> creds)
throws DataProviderSanitizationFailedException {
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // }
import java.util.ArrayList; import java.util.Collection; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.springframework.beans.factory.annotation.Autowired;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceBindingManager { @Autowired
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java import java.util.ArrayList; import java.util.Collection; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.springframework.beans.factory.annotation.Autowired; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceBindingManager { @Autowired
private BindingRepository repo;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // }
import java.util.ArrayList; import java.util.Collection; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.springframework.beans.factory.annotation.Autowired;
package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceBindingManager { @Autowired private BindingRepository repo; public LCServiceInstanceBindingManager(BindingRepository repo) { this.repo = repo; } public Collection<ServiceInstanceBinding> getBindings() { Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); repo.findAll().forEach(t -> bindings.add(convert(t))); return bindings; } public ServiceInstanceBinding getBinding(String bindingId) { return convert(repo.findOne(bindingId)); } public ServiceInstanceBinding removeBinding(String bindingId) {
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/model/BindingEntity.java // @Entity // public class BindingEntity { // // @Id // private String id; // private String appGuid; // private String bindingId; // private String serviceInstanceId; // private String drainUrl; // // public BindingEntity() { // } // // public BindingEntity(ServiceInstanceBinding binding) { // setAppGuid(binding.getAppGuid()); // setBindingId(binding.getId()); // setServiceInstanceId(binding.getServiceInstanceId()); // setDrainUrl(binding.getSyslogDrainUrl()); // this.setId(binding.getId()); // } // // public String getAppGuid() { // return appGuid; // } // // private void setAppGuid(String appGuid) { // this.appGuid = appGuid; // } // // public String getBindingId() { // return bindingId; // } // // private void setBindingId(String bindingId) { // this.bindingId = bindingId; // } // // public String getServiceInstanceId() { // return serviceInstanceId; // } // // private void setServiceInstanceId(String serviceInstanceId) { // this.serviceInstanceId = serviceInstanceId; // } // // public String getDrainUrl() { // return drainUrl; // } // // private void setDrainUrl(String drainUrl) { // this.drainUrl = drainUrl; // } // // public String getId() { // return id; // } // // private void setId(String id) { // this.id = id; // } // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/repo/BindingRepository.java // @RepositoryRestResource(collectionResourceRel = "bindings", path = "bindings") // public interface BindingRepository extends // PagingAndSortingRepository<BindingEntity, String> { // // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/service/LCServiceInstanceBindingManager.java import java.util.ArrayList; import java.util.Collection; import org.cloudfoundry.community.servicebroker.datalifecycle.model.BindingEntity; import org.cloudfoundry.community.servicebroker.datalifecycle.repo.BindingRepository; import org.cloudfoundry.community.servicebroker.model.ServiceInstanceBinding; import org.springframework.beans.factory.annotation.Autowired; package org.cloudfoundry.community.servicebroker.datalifecycle.service; public class LCServiceInstanceBindingManager { @Autowired private BindingRepository repo; public LCServiceInstanceBindingManager(BindingRepository repo) { this.repo = repo; } public Collection<ServiceInstanceBinding> getBindings() { Collection<ServiceInstanceBinding> bindings = new ArrayList<ServiceInstanceBinding>(); repo.findAll().forEach(t -> bindings.add(convert(t))); return bindings; } public ServiceInstanceBinding getBinding(String bindingId) { return convert(repo.findOne(bindingId)); } public ServiceInstanceBinding removeBinding(String bindingId) {
BindingEntity binding = repo.findOne(bindingId);
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/AWSCopyProviderConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSCopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSHelper; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.services.ec2.AmazonEC2Client;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class AWSCopyProviderConfig { @Value("#{environment.PROD_DB_USER}") private String username; @Value("#{environment.PROD_DB_PASSWORD}") private String password; @Value("#{environment.PROD_DB_URI}") private String uri; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstance; @Value("#{environment.SUBNET_ID}") private String subnetId; @Autowired private AmazonEC2Client ec2Client; @Autowired
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/AWSCopyProviderConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSCopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSHelper; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.services.ec2.AmazonEC2Client; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class AWSCopyProviderConfig { @Value("#{environment.PROD_DB_USER}") private String username; @Value("#{environment.PROD_DB_PASSWORD}") private String password; @Value("#{environment.PROD_DB_URI}") private String uri; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstance; @Value("#{environment.SUBNET_ID}") private String subnetId; @Autowired private AmazonEC2Client ec2Client; @Autowired
private HostUtils hostUtils;
krujos/data-lifecycle-service-broker
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/AWSCopyProviderConfig.java
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // }
import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSCopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSHelper; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.services.ec2.AmazonEC2Client;
package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class AWSCopyProviderConfig { @Value("#{environment.PROD_DB_USER}") private String username; @Value("#{environment.PROD_DB_PASSWORD}") private String password; @Value("#{environment.PROD_DB_URI}") private String uri; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstance; @Value("#{environment.SUBNET_ID}") private String subnetId; @Autowired private AmazonEC2Client ec2Client; @Autowired private HostUtils hostUtils; @Value("#{environment.BOOT_CHECK_PORT}") private int bootCheckPort; @Bean
// Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/provider/CopyProvider.java // public interface CopyProvider { // // /** // * Create a copy of the source instance. The implementer should inject that // * through an environment variable or other means. Upon the copy will be // * launched and accessible to clients. // * // * @param instanceId // * to create a copy of // * @return the id of the new copy. // * @throws ServiceBrokerException // * on error // */ // String createCopy(String instanceId) // throws ServiceBrokerException; // // /** // * Remove a copy from the iaas. The expectation is that all artifacts // * associated with the copy (snapshots, ami's etc) are cleaned up // * // * @param instance // * to delete // * @throws ServiceBrokerException // * on error // */ // void deleteCopy(final String instance) // throws ServiceBrokerException; // // /** // * Return the creds hash associated with service brokers. Should contain a // * URI, username, password or whatever makes sense for your service. Will be // * injected into your app. // */ // Map<String, Object> getCreds(final String instance) // throws ServiceBrokerException; // } // // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/utils/HostUtils.java // public class HostUtils { // private Logger logger = Logger.getLogger(HostUtils.class); // // public boolean waitForBoot(String ip, int port) // throws ServiceBrokerException { // // logger.info("Waiting for " + ip + " to boot."); // for (int i = 8; i > 0; --i) { // try { // try { // Thread.sleep(20000); // } catch (InterruptedException e1) { // throw new ServiceBrokerException( // "Internal Error! Something went wrong sleeping the threads!"); // } // logger.info("Attempting to connect to " + ip + " on port " // + port); // Socket socket = new Socket(); // SocketAddress addr = new InetSocketAddress( // Inet4Address.getByName(ip), port); // socket.connect(addr, 10000); // boolean connected = socket.isConnected(); // socket.close(); // if (connected) { // logger.info(ip + "is responding on " + port); // return true; // } // } catch (IOException e) { // logger.error(ip + " is not responding on " + port + " " + i // + " retires remaning."); // } // } // // return false; // } // } // Path: src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/config/AWSCopyProviderConfig.java import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSCopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.aws.AWSHelper; import org.cloudfoundry.community.servicebroker.datalifecycle.provider.CopyProvider; import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.services.ec2.AmazonEC2Client; package org.cloudfoundry.community.servicebroker.datalifecycle.config; @Configuration class AWSCopyProviderConfig { @Value("#{environment.PROD_DB_USER}") private String username; @Value("#{environment.PROD_DB_PASSWORD}") private String password; @Value("#{environment.PROD_DB_URI}") private String uri; @Value("#{environment.SOURCE_INSTANCE_ID}") private String sourceInstance; @Value("#{environment.SUBNET_ID}") private String subnetId; @Autowired private AmazonEC2Client ec2Client; @Autowired private HostUtils hostUtils; @Value("#{environment.BOOT_CHECK_PORT}") private int bootCheckPort; @Bean
CopyProvider copyProvider() {
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;
package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService {
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService {
private final MaUserService userService;
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;
package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService { private final MaUserService userService; @Autowired public CurrentUserDetailsService(MaUserService userService) { this.userService = userService; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService { private final MaUserService userService; @Autowired public CurrentUserDetailsService(MaUserService userService) { this.userService = userService; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
MaUser user = userService.getMaUserByName(name);
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;
package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService { private final MaUserService userService; @Autowired public CurrentUserDetailsService(MaUserService userService) { this.userService = userService; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { MaUser user = userService.getMaUserByName(name); if(user == null) { throw new UsernameNotFoundException(name + " not found"); }
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/service/currentUser/CurrentUserDetailsService.java import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.CurrentUser; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ @Service public class CurrentUserDetailsService implements UserDetailsService { private final MaUserService userService; @Autowired public CurrentUserDetailsService(MaUserService userService) { this.userService = userService; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { MaUser user = userService.getMaUserByName(name); if(user == null) { throw new UsernameNotFoundException(name + " not found"); }
return new CurrentUser(user);
Myazure/weixin_component
src/main/java/org/myazure/weixin/controller/UserController.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java // @Component // public class MaUserFormValidator implements Validator { // // private final MaUserService userService; // // @Autowired // public MaUserFormValidator(MaUserService userService) { // this.userService = userService; // } // // @Override // public boolean supports(Class<?> clazz) { // return clazz.equals(MaUserEntity.class); // } // // @Override // public void validate(Object target, Errors errors) { // MaUserEntity form = (MaUserEntity) target; // validatePasswords(errors, form); // validateName(errors, form); // } // // private void validatePasswords(Errors errors, MaUserEntity form) { // if (!form.getPassword().equals(form.getPasswordRepeated())) { // errors.rejectValue("password", "password", "Passwords do not match"); // } // } // // private void validateName(Errors errors, MaUserEntity form) { // if (userService.getMaUserByName(form.getUserName()) != null) { // errors.rejectValue("userName", "userName", "User with this name already exists"); // } // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import java.util.List; import java.util.NoSuchElementException; import javax.validation.Valid; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.domain.validator.MaUserFormValidator; import org.myazure.weixin.service.MaUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
package org.myazure.weixin.controller; /** * * @author WangZhen * */ @Controller public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java // @Component // public class MaUserFormValidator implements Validator { // // private final MaUserService userService; // // @Autowired // public MaUserFormValidator(MaUserService userService) { // this.userService = userService; // } // // @Override // public boolean supports(Class<?> clazz) { // return clazz.equals(MaUserEntity.class); // } // // @Override // public void validate(Object target, Errors errors) { // MaUserEntity form = (MaUserEntity) target; // validatePasswords(errors, form); // validateName(errors, form); // } // // private void validatePasswords(Errors errors, MaUserEntity form) { // if (!form.getPassword().equals(form.getPasswordRepeated())) { // errors.rejectValue("password", "password", "Passwords do not match"); // } // } // // private void validateName(Errors errors, MaUserEntity form) { // if (userService.getMaUserByName(form.getUserName()) != null) { // errors.rejectValue("userName", "userName", "User with this name already exists"); // } // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/controller/UserController.java import java.util.List; import java.util.NoSuchElementException; import javax.validation.Valid; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.domain.validator.MaUserFormValidator; import org.myazure.weixin.service.MaUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; package org.myazure.weixin.controller; /** * * @author WangZhen * */ @Controller public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final MaUserService userService;
Myazure/weixin_component
src/main/java/org/myazure/weixin/controller/UserController.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java // @Component // public class MaUserFormValidator implements Validator { // // private final MaUserService userService; // // @Autowired // public MaUserFormValidator(MaUserService userService) { // this.userService = userService; // } // // @Override // public boolean supports(Class<?> clazz) { // return clazz.equals(MaUserEntity.class); // } // // @Override // public void validate(Object target, Errors errors) { // MaUserEntity form = (MaUserEntity) target; // validatePasswords(errors, form); // validateName(errors, form); // } // // private void validatePasswords(Errors errors, MaUserEntity form) { // if (!form.getPassword().equals(form.getPasswordRepeated())) { // errors.rejectValue("password", "password", "Passwords do not match"); // } // } // // private void validateName(Errors errors, MaUserEntity form) { // if (userService.getMaUserByName(form.getUserName()) != null) { // errors.rejectValue("userName", "userName", "User with this name already exists"); // } // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import java.util.List; import java.util.NoSuchElementException; import javax.validation.Valid; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.domain.validator.MaUserFormValidator; import org.myazure.weixin.service.MaUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
package org.myazure.weixin.controller; /** * * @author WangZhen * */ @Controller public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); private final MaUserService userService;
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java // @Component // public class MaUserFormValidator implements Validator { // // private final MaUserService userService; // // @Autowired // public MaUserFormValidator(MaUserService userService) { // this.userService = userService; // } // // @Override // public boolean supports(Class<?> clazz) { // return clazz.equals(MaUserEntity.class); // } // // @Override // public void validate(Object target, Errors errors) { // MaUserEntity form = (MaUserEntity) target; // validatePasswords(errors, form); // validateName(errors, form); // } // // private void validatePasswords(Errors errors, MaUserEntity form) { // if (!form.getPassword().equals(form.getPasswordRepeated())) { // errors.rejectValue("password", "password", "Passwords do not match"); // } // } // // private void validateName(Errors errors, MaUserEntity form) { // if (userService.getMaUserByName(form.getUserName()) != null) { // errors.rejectValue("userName", "userName", "User with this name already exists"); // } // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/controller/UserController.java import java.util.List; import java.util.NoSuchElementException; import javax.validation.Valid; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.domain.validator.MaUserFormValidator; import org.myazure.weixin.service.MaUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; package org.myazure.weixin.controller; /** * * @author WangZhen * */ @Controller public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); private final MaUserService userService;
private final MaUserFormValidator userCreateFormValidator;
Myazure/weixin_component
src/main/java/org/myazure/weixin/handlers/VerifyTicketHandler.java
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // }
import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import weixin.popular.bean.component.ComponentReceiveXML;
package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class VerifyTicketHandler { private static final Logger LOG = LoggerFactory.getLogger(VerifyTicketHandler.class); @Autowired private StringRedisTemplate redisTemplate; @Autowired private AuthorizeHandler authorizeHandler; /** * 刷新凭证 * * @param eventMessage */ public void refreshVerifyTicket(ComponentReceiveXML eventMessage) { // Update component verify ticket in memory
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // } // Path: src/main/java/org/myazure/weixin/handlers/VerifyTicketHandler.java import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import weixin.popular.bean.component.ComponentReceiveXML; package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class VerifyTicketHandler { private static final Logger LOG = LoggerFactory.getLogger(VerifyTicketHandler.class); @Autowired private StringRedisTemplate redisTemplate; @Autowired private AuthorizeHandler authorizeHandler; /** * 刷新凭证 * * @param eventMessage */ public void refreshVerifyTicket(ComponentReceiveXML eventMessage) { // Update component verify ticket in memory
MyazureConstants.MYAZURE_COMPONENT_VERIFY_TICKET = eventMessage.getComponentVerifyTicket();
Myazure/weixin_component
src/main/java/org/myazure/weixin/handlers/VerifyTicketHandler.java
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // }
import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import weixin.popular.bean.component.ComponentReceiveXML;
package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class VerifyTicketHandler { private static final Logger LOG = LoggerFactory.getLogger(VerifyTicketHandler.class); @Autowired private StringRedisTemplate redisTemplate; @Autowired private AuthorizeHandler authorizeHandler; /** * 刷新凭证 * * @param eventMessage */ public void refreshVerifyTicket(ComponentReceiveXML eventMessage) { // Update component verify ticket in memory MyazureConstants.MYAZURE_COMPONENT_VERIFY_TICKET = eventMessage.getComponentVerifyTicket(); // Refresh component access token LOG.info("[Myazure Weixin]: Refresh component access token from redis.");
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // } // Path: src/main/java/org/myazure/weixin/handlers/VerifyTicketHandler.java import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import weixin.popular.bean.component.ComponentReceiveXML; package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class VerifyTicketHandler { private static final Logger LOG = LoggerFactory.getLogger(VerifyTicketHandler.class); @Autowired private StringRedisTemplate redisTemplate; @Autowired private AuthorizeHandler authorizeHandler; /** * 刷新凭证 * * @param eventMessage */ public void refreshVerifyTicket(ComponentReceiveXML eventMessage) { // Update component verify ticket in memory MyazureConstants.MYAZURE_COMPONENT_VERIFY_TICKET = eventMessage.getComponentVerifyTicket(); // Refresh component access token LOG.info("[Myazure Weixin]: Refresh component access token from redis.");
String accessToken = redisTemplate.opsForValue().get(WeixinConstans.COMPONENT_ACCESS_TOKEN_KEY);
Myazure/weixin_component
src/main/java/org/myazure/weixin/controller/CurrentUserControllerAdvice.java
// Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // }
import org.myazure.weixin.domain.CurrentUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute;
package org.myazure.weixin.controller; /** * * @author WangZhen * */ @ControllerAdvice public class CurrentUserControllerAdvice { private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserControllerAdvice.class); @ModelAttribute("currentUser")
// Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // Path: src/main/java/org/myazure/weixin/controller/CurrentUserControllerAdvice.java import org.myazure.weixin.domain.CurrentUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; package org.myazure.weixin.controller; /** * * @author WangZhen * */ @ControllerAdvice public class CurrentUserControllerAdvice { private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserControllerAdvice.class); @ModelAttribute("currentUser")
public CurrentUser getCurrentUser(Authentication authentication) {
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/currentUser/CurrentUserServiceImpl.java
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // }
import org.myazure.weixin.domain.MaRole; import org.myazure.weixin.domain.CurrentUser;
package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ public class CurrentUserServiceImpl implements CurrentUserService { @Override
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // Path: src/main/java/org/myazure/weixin/service/currentUser/CurrentUserServiceImpl.java import org.myazure.weixin.domain.MaRole; import org.myazure.weixin.domain.CurrentUser; package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ public class CurrentUserServiceImpl implements CurrentUserService { @Override
public boolean canAccessUser(CurrentUser currentUser, Long userId) {
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/currentUser/CurrentUserServiceImpl.java
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // }
import org.myazure.weixin.domain.MaRole; import org.myazure.weixin.domain.CurrentUser;
package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ public class CurrentUserServiceImpl implements CurrentUserService { @Override public boolean canAccessUser(CurrentUser currentUser, Long userId) { return currentUser != null
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // } // // Path: src/main/java/org/myazure/weixin/domain/CurrentUser.java // public class CurrentUser extends org.springframework.security.core.userdetails.User { // // /** // * // */ // private static final long serialVersionUID = 1L; // private MaUser user; // // public CurrentUser(MaUser user) { // super(user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole().toString())); // this.user = user; // } // // public MaUser getUser() { // return user; // } // // public Long getId() { // return user.getId(); // } // // public MaRole getRole() { // return user.getRole(); // } // // @Override // public String toString() { // return "CurrentUser{" + // "user=" + user + // "} " + super.toString(); // } // } // Path: src/main/java/org/myazure/weixin/service/currentUser/CurrentUserServiceImpl.java import org.myazure.weixin.domain.MaRole; import org.myazure.weixin.domain.CurrentUser; package org.myazure.weixin.service.currentUser; /** * @author WangZhen */ public class CurrentUserServiceImpl implements CurrentUserService { @Override public boolean canAccessUser(CurrentUser currentUser, Long userId) { return currentUser != null
&& (currentUser.getRole() == MaRole.ADMIN || currentUser.getId().equals(userId));
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/MaUserService.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // }
import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity;
package org.myazure.weixin.service; /** * * @author WangZhen * */ public interface MaUserService { MaUser getMaUserById(long id); MaUser getMaUserByName(String name); Collection<MaUser> getAllMaUsers();
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // Path: src/main/java/org/myazure/weixin/service/MaUserService.java import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; package org.myazure.weixin.service; /** * * @author WangZhen * */ public interface MaUserService { MaUser getMaUserById(long id); MaUser getMaUserByName(String name); Collection<MaUser> getAllMaUsers();
MaUser create(MaUserEntity form);
Myazure/weixin_component
src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java
// Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator;
package org.myazure.weixin.domain.validator; /** * @author WangZhen */ @Component public class MaUserFormValidator implements Validator {
// Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; package org.myazure.weixin.domain.validator; /** * @author WangZhen */ @Component public class MaUserFormValidator implements Validator {
private final MaUserService userService;
Myazure/weixin_component
src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java
// Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // }
import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator;
package org.myazure.weixin.domain.validator; /** * @author WangZhen */ @Component public class MaUserFormValidator implements Validator { private final MaUserService userService; @Autowired public MaUserFormValidator(MaUserService userService) { this.userService = userService; } @Override public boolean supports(Class<?> clazz) {
// Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/service/MaUserService.java // public interface MaUserService { // // MaUser getMaUserById(long id); // // MaUser getMaUserByName(String name); // // Collection<MaUser> getAllMaUsers(); // // MaUser create(MaUserEntity form); // } // Path: src/main/java/org/myazure/weixin/domain/validator/MaUserFormValidator.java import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.service.MaUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; package org.myazure.weixin.domain.validator; /** * @author WangZhen */ @Component public class MaUserFormValidator implements Validator { private final MaUserService userService; @Autowired public MaUserFormValidator(MaUserService userService) { this.userService = userService; } @Override public boolean supports(Class<?> clazz) {
return clazz.equals(MaUserEntity.class);
Myazure/weixin_component
src/main/java/org/myazure/weixin/lisenner/SystemInitListener.java
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // }
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.qq.weixin.mp.aes.AesException; import com.qq.weixin.mp.aes.WXBizMsgCrypt; import weixin.popular.api.API; import weixin.popular.client.LocalHttpClient; import weixin.popular.support.TokenManager;
package org.myazure.weixin.lisenner; /** * Token 监听器 * * @author WangZhen * */ @Component("servletContextListener") public class SystemInitListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(SystemInitListener.class); @Value("${weixin.compAppId}") protected String MYAZURE_APP_ID; @Value("${weixin.compAppSecret}") protected String MYAZURE_APP_SECRET; @Value("${weixin.encode.token}") protected String MYAZURE_ENCODE_TOKEN; @Value("${weixin.encode.key}") protected String MYAZURE_ENCODE_KEY; @Value("${myazure.appUrl}") protected String MYAZURE_APP_URL; @Value("${myazure.serverId}") protected String MYAZURE_SERVER_ID; @Autowired private StringRedisTemplate redisTemplate; @Override public void contextInitialized(ServletContextEvent sce) {
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // } // Path: src/main/java/org/myazure/weixin/lisenner/SystemInitListener.java import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.qq.weixin.mp.aes.AesException; import com.qq.weixin.mp.aes.WXBizMsgCrypt; import weixin.popular.api.API; import weixin.popular.client.LocalHttpClient; import weixin.popular.support.TokenManager; package org.myazure.weixin.lisenner; /** * Token 监听器 * * @author WangZhen * */ @Component("servletContextListener") public class SystemInitListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(SystemInitListener.class); @Value("${weixin.compAppId}") protected String MYAZURE_APP_ID; @Value("${weixin.compAppSecret}") protected String MYAZURE_APP_SECRET; @Value("${weixin.encode.token}") protected String MYAZURE_ENCODE_TOKEN; @Value("${weixin.encode.key}") protected String MYAZURE_ENCODE_KEY; @Value("${myazure.appUrl}") protected String MYAZURE_APP_URL; @Value("${myazure.serverId}") protected String MYAZURE_SERVER_ID; @Autowired private StringRedisTemplate redisTemplate; @Override public void contextInitialized(ServletContextEvent sce) {
MyazureConstants.MYAZURE_APP_ID = MYAZURE_APP_ID;
Myazure/weixin_component
src/main/java/org/myazure/weixin/lisenner/SystemInitListener.java
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // }
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.qq.weixin.mp.aes.AesException; import com.qq.weixin.mp.aes.WXBizMsgCrypt; import weixin.popular.api.API; import weixin.popular.client.LocalHttpClient; import weixin.popular.support.TokenManager;
package org.myazure.weixin.lisenner; /** * Token 监听器 * * @author WangZhen * */ @Component("servletContextListener") public class SystemInitListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(SystemInitListener.class); @Value("${weixin.compAppId}") protected String MYAZURE_APP_ID; @Value("${weixin.compAppSecret}") protected String MYAZURE_APP_SECRET; @Value("${weixin.encode.token}") protected String MYAZURE_ENCODE_TOKEN; @Value("${weixin.encode.key}") protected String MYAZURE_ENCODE_KEY; @Value("${myazure.appUrl}") protected String MYAZURE_APP_URL; @Value("${myazure.serverId}") protected String MYAZURE_SERVER_ID; @Autowired private StringRedisTemplate redisTemplate; @Override public void contextInitialized(ServletContextEvent sce) { MyazureConstants.MYAZURE_APP_ID = MYAZURE_APP_ID; MyazureConstants.MYAZURE_APP_SECRET = MYAZURE_APP_SECRET; MyazureConstants.MYAZURE_ENCODE_TOKEN = MYAZURE_ENCODE_TOKEN; MyazureConstants.MYAZURE_ENCODE_KEY = MYAZURE_ENCODE_KEY; MyazureConstants.MYAZURE_APP_URL = MYAZURE_APP_URL; MyazureConstants.MYAZURE_SERVER_ID = MYAZURE_SERVER_ID; API.defaultMode(API.MODE_POPULAR);
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // // Path: src/main/java/org/myazure/weixin/constant/WeixinConstans.java // public class WeixinConstans { // public static ExpireKey expireKey = new DefaultExpireKey(); // public static final String BASE_WEIXIN_API_URI = "https://api.weixin.qq.com"; // public static final String PARAM_ACCESS_TOKEN = "access_token"; // public static final String TOKEN_STRING = "token"; // public static final String COMPONENT_ACCESS_TOKEN_KEY = "component.access.token"; // public static final String PRE_AUTH_CODE_KEY = "pre.auth.code"; // public static final String AUTHORIZER_ACCESS_TOKEN_KEY = "authorizer.access.token"; // public static final String AUTHORIZER_REFRESH_TOKEN_KEY = "authorizer.refresh.token"; // // WECHAT MSG INFO // public static final int FUNCTION_MSG_MANAGEMENT = 1;// 消息管理权限 // public static final int FUNCTION_USER_MANAGEMENT = 2; // public static final int FUNCTION_ACCOUNT_SERVICE_MANAGEMENT = 3; // public static final int FUNCTION_WEB_SERVICE_MANAGEMENT = 4; // public static final int FUNCTION_WEIXIN_STORE_MANAGEMENT = 5; // public static final int FUNCTION_VICTOR_CUSTORMER_SERVICE_MANAGEMENT = 6; // public static final int FUNCTION_MASS_NOTIFICATION_MANAGEMENT = 7; // public static final int FUNCTION_WEIXIN_CARD_MANAGEMENT = 8; // public static final int FUNCTION_SWEEP_MANAGEMENT = 9; // public static final int FUNCTION_EVEN_FIWI_MANAGEMENT = 10; // public static final int FUNCTION_MATERIAL_MANAGEMENT = 11; // public static final int FUNCTION_WECHAT_SHAKE_PERIPHERAL_MANAGEMENT = 12; // public static final int FUNCTION_WECHAT_STORE_MANAGEMENT = 13; // public static final int FUNCTION_PAYMENT_MANAGEMENT = 14; // public static final int FUNCTION_CUSTOM_MENU_MANAGEMENT = 15; // } // Path: src/main/java/org/myazure/weixin/lisenner/SystemInitListener.java import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.myazure.weixin.constant.MyazureConstants; import org.myazure.weixin.constant.WeixinConstans; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.qq.weixin.mp.aes.AesException; import com.qq.weixin.mp.aes.WXBizMsgCrypt; import weixin.popular.api.API; import weixin.popular.client.LocalHttpClient; import weixin.popular.support.TokenManager; package org.myazure.weixin.lisenner; /** * Token 监听器 * * @author WangZhen * */ @Component("servletContextListener") public class SystemInitListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(SystemInitListener.class); @Value("${weixin.compAppId}") protected String MYAZURE_APP_ID; @Value("${weixin.compAppSecret}") protected String MYAZURE_APP_SECRET; @Value("${weixin.encode.token}") protected String MYAZURE_ENCODE_TOKEN; @Value("${weixin.encode.key}") protected String MYAZURE_ENCODE_KEY; @Value("${myazure.appUrl}") protected String MYAZURE_APP_URL; @Value("${myazure.serverId}") protected String MYAZURE_SERVER_ID; @Autowired private StringRedisTemplate redisTemplate; @Override public void contextInitialized(ServletContextEvent sce) { MyazureConstants.MYAZURE_APP_ID = MYAZURE_APP_ID; MyazureConstants.MYAZURE_APP_SECRET = MYAZURE_APP_SECRET; MyazureConstants.MYAZURE_ENCODE_TOKEN = MYAZURE_ENCODE_TOKEN; MyazureConstants.MYAZURE_ENCODE_KEY = MYAZURE_ENCODE_KEY; MyazureConstants.MYAZURE_APP_URL = MYAZURE_APP_URL; MyazureConstants.MYAZURE_SERVER_ID = MYAZURE_SERVER_ID; API.defaultMode(API.MODE_POPULAR);
MyazureConstants.MYAZURE_COMPONENT_ACCESS_TOKEN = redisTemplate.opsForValue().get(WeixinConstans.COMPONENT_ACCESS_TOKEN_KEY);
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // }
import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service;
package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder;
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // } // Path: src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder;
private final MaUserRepository userRepository;
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // }
import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service;
package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder; private final MaUserRepository userRepository; @Autowired public MaUserServiceImpl(MaUserRepository userRepository) { this.userRepository = userRepository; } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator")
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // } // Path: src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder; private final MaUserRepository userRepository; @Autowired public MaUserServiceImpl(MaUserRepository userRepository) { this.userRepository = userRepository; } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator")
public MaUser getMaUserById(long id) {
Myazure/weixin_component
src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // }
import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service;
package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder; private final MaUserRepository userRepository; @Autowired public MaUserServiceImpl(MaUserRepository userRepository) { this.userRepository = userRepository; } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator") public MaUser getMaUserById(long id) { LOGGER.info("[Myazure Weixin]: getMaUserById()"); return userRepository.findOne(id); } @Override public MaUser getMaUserByName(String name) { return userRepository.findOneByUserName(name); } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator") public Collection<MaUser> getAllMaUsers() { LOGGER.info("[Myazure Weixin]: getAllAdUsers()"); return (Collection<MaUser>) userRepository.findAll(new Sort("userName")); } @Override
// Path: src/main/java/org/myazure/weixin/domain/MaUser.java // @Entity // @Table(name = "myazure_weixin_user") // public class MaUser extends BaseEntity { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private long id; // // @Column(name = "username", nullable = false, unique = true) // private String userName; // // @Column(name = "password", nullable = false) // private String password; // // @Column(name = "role", nullable = false) // @Enumerated(EnumType.STRING) // private MaRole role; // // @Column(name = "active", columnDefinition = "BIT", length = 1) // private boolean active = false; // // public MaUser() { // // } // // public MaUser(String userName, String password, MaRole role) { // this.userName = userName; // this.password = password; // this.role = role; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // } // // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java // public class MaUserEntity { // // @NotEmpty // private Long id; // // @NotEmpty // private String userName = ""; // // private String password = ""; // // private String passwordRepeated = ""; // // @NotNull // private MaRole role = MaRole.USER; // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getPasswordRepeated() { // return passwordRepeated; // } // // public void setPasswordRepeated(String passwordRepeated) { // this.passwordRepeated = passwordRepeated; // } // // public MaRole getRole() { // return role; // } // // public void setRole(MaRole role) { // this.role = role; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // } // // Path: src/main/java/org/myazure/weixin/repository/MaUserRepository.java // public interface MaUserRepository extends PagingAndSortingRepository<MaUser, Long> { // // MaUser findOneByUserName(String userName); // } // Path: src/main/java/org/myazure/weixin/service/MaUserServiceImpl.java import java.util.Collection; import org.myazure.weixin.domain.MaUser; import org.myazure.weixin.domain.entity.MaUserEntity; import org.myazure.weixin.repository.MaUserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; package org.myazure.weixin.service; /** * * @author WangZhen * */ @Service public class MaUserServiceImpl implements MaUserService { private static final Logger LOGGER = LoggerFactory.getLogger(MaUserServiceImpl.class); @Autowired private BCryptPasswordEncoder passwordEncoder; private final MaUserRepository userRepository; @Autowired public MaUserServiceImpl(MaUserRepository userRepository) { this.userRepository = userRepository; } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator") public MaUser getMaUserById(long id) { LOGGER.info("[Myazure Weixin]: getMaUserById()"); return userRepository.findOne(id); } @Override public MaUser getMaUserByName(String name) { return userRepository.findOneByUserName(name); } @Override @Cacheable(value = "userCache",keyGenerator = "wiselyKeyGenerator") public Collection<MaUser> getAllMaUsers() { LOGGER.info("[Myazure Weixin]: getAllAdUsers()"); return (Collection<MaUser>) userRepository.findAll(new Sort("userName")); } @Override
public MaUser create(MaUserEntity form) {
Myazure/weixin_component
src/main/java/org/myazure/weixin/MyazureWeiXin.java
// Path: src/main/java/org/myazure/weixin/configuration/AppUrlService.java // public class AppUrlService { // // @Value("${myazure.appUrl}") // private String appUrl; // // public AppUrlService() { // // } // // public void setAppUrl(String appUrl) { // this.appUrl = appUrl; // } // // public String getAppUrl() { // return appUrl; // } // } // // Path: src/main/java/org/myazure/weixin/configuration/MyazureEmbeddedServletContainerCustomizer.java // public class MyazureEmbeddedServletContainerCustomizer implements EmbeddedServletContainerCustomizer { // // private static final Logger LOG = LoggerFactory.getLogger(MyazureEmbeddedServletContainerCustomizer.class); // // @Value("${servlet.container.maxThreads}") // private int MAX_THREADS; // // @Override // public void customize(ConfigurableEmbeddedServletContainer factory) { // if (factory instanceof TomcatEmbeddedServletContainerFactory) { // customizeTomcat((TomcatEmbeddedServletContainerFactory) factory); // } // } // // public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) { // factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { // @Override // public void customize(Connector connector) { // Object defaultMaxThreads = connector.getAttribute("maxThreads"); // connector.setAttribute("maxThreads", MAX_THREADS); // LOG.info("Changed Tomcat connector maxThreads from " + defaultMaxThreads + " to " + MAX_THREADS); // } // }); // } // }
import org.myazure.weixin.configuration.AppUrlService; import org.myazure.weixin.configuration.MyazureEmbeddedServletContainerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate;
package org.myazure.weixin; /** * * @author WangZhen * */ @Configuration @ComponentScan @EnableAutoConfiguration @EnableTransactionManagement @EnableJpaRepositories @EnableJpaAuditing @SpringBootApplication // @EnableCaching public class MyazureWeiXin { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(MyazureWeiXin.class); @Bean public RestTemplate restTemplate() { return new RestTemplate(clientHttpRequestFactory()); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean
// Path: src/main/java/org/myazure/weixin/configuration/AppUrlService.java // public class AppUrlService { // // @Value("${myazure.appUrl}") // private String appUrl; // // public AppUrlService() { // // } // // public void setAppUrl(String appUrl) { // this.appUrl = appUrl; // } // // public String getAppUrl() { // return appUrl; // } // } // // Path: src/main/java/org/myazure/weixin/configuration/MyazureEmbeddedServletContainerCustomizer.java // public class MyazureEmbeddedServletContainerCustomizer implements EmbeddedServletContainerCustomizer { // // private static final Logger LOG = LoggerFactory.getLogger(MyazureEmbeddedServletContainerCustomizer.class); // // @Value("${servlet.container.maxThreads}") // private int MAX_THREADS; // // @Override // public void customize(ConfigurableEmbeddedServletContainer factory) { // if (factory instanceof TomcatEmbeddedServletContainerFactory) { // customizeTomcat((TomcatEmbeddedServletContainerFactory) factory); // } // } // // public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) { // factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { // @Override // public void customize(Connector connector) { // Object defaultMaxThreads = connector.getAttribute("maxThreads"); // connector.setAttribute("maxThreads", MAX_THREADS); // LOG.info("Changed Tomcat connector maxThreads from " + defaultMaxThreads + " to " + MAX_THREADS); // } // }); // } // } // Path: src/main/java/org/myazure/weixin/MyazureWeiXin.java import org.myazure.weixin.configuration.AppUrlService; import org.myazure.weixin.configuration.MyazureEmbeddedServletContainerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; package org.myazure.weixin; /** * * @author WangZhen * */ @Configuration @ComponentScan @EnableAutoConfiguration @EnableTransactionManagement @EnableJpaRepositories @EnableJpaAuditing @SpringBootApplication // @EnableCaching public class MyazureWeiXin { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(MyazureWeiXin.class); @Bean public RestTemplate restTemplate() { return new RestTemplate(clientHttpRequestFactory()); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean
public AppUrlService appUrlService() {
Myazure/weixin_component
src/main/java/org/myazure/weixin/handlers/QrCodeHandler.java
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // }
import java.awt.image.BufferedImage; import org.myazure.weixin.constant.MyazureConstants; import weixin.popular.api.QrcodeAPI; import weixin.popular.bean.qrcode.QrcodeTicket;
package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class QrCodeHandler { /** * 创建 二维码 * * @param access_token * access_token * @param expire_seconds * 最大不超过604800秒(即30天) * @param scene_id * 场景值ID,32位非0整型 最多10万个 * @return QrcodeTicket */ public QrcodeTicket qrcodeCreate(String JSONData, int expire_seconds, int scene_id) { if (expire_seconds > 0) {
// Path: src/main/java/org/myazure/weixin/constant/MyazureConstants.java // public class MyazureConstants { // public static final String LOG_SPLIT_LINE = "========================MYAZURE====SPLIT====LINE========================"; // public static final String MYAZURE_WEIXIN_ADMIN_APPID="wx86c66f041e334ba4"; // public static final String MYAZURE_WEIXIN_ADMIN_APPSECRET="dbee2c24cc0dd3c8bb0805de2f4e4606"; // public static final String MYAZURE_WEIXIN_ADMIN_OPENID="o14wavxo7TN_zRBDD3c-mIigYR4U"; // // public static String MYAZURE_SERVER_ID; // public static String MYAZURE_APP_ID; // public static String MYAZURE_APP_SECRET; // public static String MYAZURE_ENCODE_TOKEN; // public static String MYAZURE_ENCODE_KEY; // public static String MYAZURE_APP_URL; // public static String MYAZURE_COMPONENT_VERIFY_TICKET; // public static String MYAZURE_COMPONENT_ACCESS_TOKEN; // public static String MYAZURE_PRE_AUTH_CODE; // public static WXBizMsgCrypt MYAZUZRE_WXBIZMSGCRYPT; // // public static final String ERR_OA_NOT_FOUNDED="OfficalAccountNotFound"; // // } // Path: src/main/java/org/myazure/weixin/handlers/QrCodeHandler.java import java.awt.image.BufferedImage; import org.myazure.weixin.constant.MyazureConstants; import weixin.popular.api.QrcodeAPI; import weixin.popular.bean.qrcode.QrcodeTicket; package org.myazure.weixin.handlers; /** * * @author WangZhen * */ public class QrCodeHandler { /** * 创建 二维码 * * @param access_token * access_token * @param expire_seconds * 最大不超过604800秒(即30天) * @param scene_id * 场景值ID,32位非0整型 最多10万个 * @return QrcodeTicket */ public QrcodeTicket qrcodeCreate(String JSONData, int expire_seconds, int scene_id) { if (expire_seconds > 0) {
return QrcodeAPI.qrcodeCreateTemp(MyazureConstants.MYAZURE_COMPONENT_ACCESS_TOKEN, expire_seconds, scene_id);
Myazure/weixin_component
src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // }
import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.myazure.weixin.domain.MaRole;
package org.myazure.weixin.domain.entity; /** * * @author WangZhen * */ public class MaUserEntity { @NotEmpty private Long id; @NotEmpty private String userName = ""; private String password = ""; private String passwordRepeated = ""; @NotNull
// Path: src/main/java/org/myazure/weixin/domain/MaRole.java // public enum MaRole { // USER, ADMIN // } // Path: src/main/java/org/myazure/weixin/domain/entity/MaUserEntity.java import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.myazure.weixin.domain.MaRole; package org.myazure.weixin.domain.entity; /** * * @author WangZhen * */ public class MaUserEntity { @NotEmpty private Long id; @NotEmpty private String userName = ""; private String password = ""; private String passwordRepeated = ""; @NotNull
private MaRole role = MaRole.USER;
StumbleUponArchive/hbase
src/test/java/org/apache/hadoop/hbase/zookeeper/TestZKTable.java
// Path: src/main/java/org/apache/hadoop/hbase/zookeeper/ZKTable.java // public static enum TableState { // ENABLED, // DISABLED, // DISABLING, // ENABLING // };
import org.apache.zookeeper.data.Stat; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.zookeeper.ZKTable.TableState; import org.apache.zookeeper.KeeperException;
assertFalse(zkt.isDisabledTable(name)); assertFalse(zkt.getDisabledTables().contains(name)); assertTrue(zkt.isTablePresent(name)); zkt.setEnabledTable(name); assertTrue(zkt.isEnabledTable(name)); assertFalse(zkt.isEnablingTable(name)); assertTrue(zkt.isTablePresent(name)); zkt.setDeletedTable(name); assertFalse(zkt.isEnabledTable(name)); assertFalse(zkt.isDisablingTable(name)); assertFalse(zkt.isDisabledTable(name)); assertFalse(zkt.isEnablingTable(name)); assertFalse(zkt.isDisablingOrDisabledTable(name)); assertFalse(zkt.isDisabledOrEnablingTable(name)); assertFalse(zkt.isTablePresent(name)); } /** * Test that ZK table writes table state in formats expected by 0.92 and 0.94 clients */ @Test public void test9294Compatibility() throws Exception { final String tableName = "test9294Compatibility"; ZooKeeperWatcher zkw = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), tableName, abortable, true); ZKTable zkt = new ZKTable(zkw); zkt.setEnabledTable(tableName); // check that current/0.94 format table has proper ENABLED format assertTrue(
// Path: src/main/java/org/apache/hadoop/hbase/zookeeper/ZKTable.java // public static enum TableState { // ENABLED, // DISABLED, // DISABLING, // ENABLING // }; // Path: src/test/java/org/apache/hadoop/hbase/zookeeper/TestZKTable.java import org.apache.zookeeper.data.Stat; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.zookeeper.ZKTable.TableState; import org.apache.zookeeper.KeeperException; assertFalse(zkt.isDisabledTable(name)); assertFalse(zkt.getDisabledTables().contains(name)); assertTrue(zkt.isTablePresent(name)); zkt.setEnabledTable(name); assertTrue(zkt.isEnabledTable(name)); assertFalse(zkt.isEnablingTable(name)); assertTrue(zkt.isTablePresent(name)); zkt.setDeletedTable(name); assertFalse(zkt.isEnabledTable(name)); assertFalse(zkt.isDisablingTable(name)); assertFalse(zkt.isDisabledTable(name)); assertFalse(zkt.isEnablingTable(name)); assertFalse(zkt.isDisablingOrDisabledTable(name)); assertFalse(zkt.isDisabledOrEnablingTable(name)); assertFalse(zkt.isTablePresent(name)); } /** * Test that ZK table writes table state in formats expected by 0.92 and 0.94 clients */ @Test public void test9294Compatibility() throws Exception { final String tableName = "test9294Compatibility"; ZooKeeperWatcher zkw = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), tableName, abortable, true); ZKTable zkt = new ZKTable(zkw); zkt.setEnabledTable(tableName); // check that current/0.94 format table has proper ENABLED format assertTrue(
ZKTableReadOnly.getTableState(zkw, zkw.masterTableZNode, tableName) == TableState.ENABLED);
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/fragments/HomeFragment.java
// Path: app/src/main/java/com/quixom/apps/deviceinfo/utilities/KeyUtil.java // public class KeyUtil { // public static final String datePattern = "dd MMM yyyy HH:mm:ss z"; // public static final String KEY_MODE = "key_mode"; // // /*** Sensor */ // public static final String KEY_SENSOR_NAME = "key_sensor_name"; // public static final String KEY_SENSOR_TYPE = "key_sensor_type"; // public static final String KEY_SENSOR_ICON = "key_sensor_icon"; // // public static float KEY_LAST_KNOWN_HUMIDITY = 0f; // // public static final int KEY_CAMERA_CODE = 101; // public static final int KEY_CALL_PERMISSION = 102; // public static final int KEY_READ_PHONE_STATE = 103; // public static final int IS_USER_COME_FROM_SYSTEM_APPS = 1; // public static final int IS_USER_COME_FROM_USER_APPS = 2; // }
import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.quixom.apps.deviceinfo.R; import com.quixom.apps.deviceinfo.utilities.KeyUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder;
@BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.tv_manufacturer) TextView tvManufacturer; @BindView(R.id.tv_brand_name) TextView tvBrand; @BindView(R.id.tv_model_number) TextView tvModel; @BindView(R.id.tv_board) TextView tvBoard; @BindView(R.id.tv_hardware) TextView tvHardware; @BindView(R.id.tv_serial_no) TextView tvSerialNo; @BindView(R.id.tv_android_id) TextView tvAndroidId; @BindView(R.id.tv_screen_resolution) TextView tvScreenResolution; @BindView(R.id.tv_boot_loader) TextView tvBootLoader; @BindView(R.id.tv_user) TextView tvUser; @BindView(R.id.tv_host) TextView tvHost; public static HomeFragment getInstance(int mode) { HomeFragment homeFragment = new HomeFragment(); Bundle bundle = new Bundle();
// Path: app/src/main/java/com/quixom/apps/deviceinfo/utilities/KeyUtil.java // public class KeyUtil { // public static final String datePattern = "dd MMM yyyy HH:mm:ss z"; // public static final String KEY_MODE = "key_mode"; // // /*** Sensor */ // public static final String KEY_SENSOR_NAME = "key_sensor_name"; // public static final String KEY_SENSOR_TYPE = "key_sensor_type"; // public static final String KEY_SENSOR_ICON = "key_sensor_icon"; // // public static float KEY_LAST_KNOWN_HUMIDITY = 0f; // // public static final int KEY_CAMERA_CODE = 101; // public static final int KEY_CALL_PERMISSION = 102; // public static final int KEY_READ_PHONE_STATE = 103; // public static final int IS_USER_COME_FROM_SYSTEM_APPS = 1; // public static final int IS_USER_COME_FROM_USER_APPS = 2; // } // Path: app/src/main/java/com/quixom/apps/deviceinfo/fragments/HomeFragment.java import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.quixom.apps.deviceinfo.R; import com.quixom.apps.deviceinfo.utilities.KeyUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.tv_manufacturer) TextView tvManufacturer; @BindView(R.id.tv_brand_name) TextView tvBrand; @BindView(R.id.tv_model_number) TextView tvModel; @BindView(R.id.tv_board) TextView tvBoard; @BindView(R.id.tv_hardware) TextView tvHardware; @BindView(R.id.tv_serial_no) TextView tvSerialNo; @BindView(R.id.tv_android_id) TextView tvAndroidId; @BindView(R.id.tv_screen_resolution) TextView tvScreenResolution; @BindView(R.id.tv_boot_loader) TextView tvBootLoader; @BindView(R.id.tv_user) TextView tvUser; @BindView(R.id.tv_host) TextView tvHost; public static HomeFragment getInstance(int mode) { HomeFragment homeFragment = new HomeFragment(); Bundle bundle = new Bundle();
bundle.putInt(KeyUtil.KEY_MODE, mode);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToBigIntegerTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigIntegerTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 10, -1); } @Test public void testValidateFail() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToBigIntegerTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigIntegerTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 10, -1); } @Test public void testValidateFail() throws Exception {
expectedEx.expect(TypeConverterException.class);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/FullMapper.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class FullMapper extends CopyBookMapperBase { public <T> byte[] serialize(T obj) { ByteBuffer buffer = ByteBuffer.wrap(new byte[this.maxRecordSize]); writeFieldsToBuffer(this.fields, buffer, obj); byte[] result = new byte[buffer.position()]; System.arraycopy(buffer.array(), 0, result, 0, buffer.position()); // Copy bytes to result array return result; } private <T> void writeFieldsToBuffer(List<CopyBookField> fields, ByteBuffer buffer, T rootObj) { for(CopyBookField field : fields) { if(field.isArray()) { Object array = field.getObject(rootObj); int arraySize = Math.max(array != null ? Array.getLength(array) : 0, field.getMinOccurs()); if(field.hasSubCopyBookFields()) { // Complex array types fx. Request[] for (int i = 0; i < arraySize; i++) { writeFieldsToBuffer(field.getSubCopyBookFields(), buffer, field.getObject(rootObj, i)); } } else { // Simple array types, fx. int[] for (int i = 0; i < arraySize; i++) { buffer.put(field.getBytes(rootObj, array, i, true)); } } } else if(field.hasSubCopyBookFields()) { // Complex type fx, Request writeFieldsToBuffer(field.getSubCopyBookFields(), buffer, field.getObject(rootObj)); } else { // Simple type fx. int byte[] bytes = field.getBytes(rootObj, true); if(bytes != null) { buffer.put(bytes); } else if(rootObj == null) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/FullMapper.java import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class FullMapper extends CopyBookMapperBase { public <T> byte[] serialize(T obj) { ByteBuffer buffer = ByteBuffer.wrap(new byte[this.maxRecordSize]); writeFieldsToBuffer(this.fields, buffer, obj); byte[] result = new byte[buffer.position()]; System.arraycopy(buffer.array(), 0, result, 0, buffer.position()); // Copy bytes to result array return result; } private <T> void writeFieldsToBuffer(List<CopyBookField> fields, ByteBuffer buffer, T rootObj) { for(CopyBookField field : fields) { if(field.isArray()) { Object array = field.getObject(rootObj); int arraySize = Math.max(array != null ? Array.getLength(array) : 0, field.getMinOccurs()); if(field.hasSubCopyBookFields()) { // Complex array types fx. Request[] for (int i = 0; i < arraySize; i++) { writeFieldsToBuffer(field.getSubCopyBookFields(), buffer, field.getObject(rootObj, i)); } } else { // Simple array types, fx. int[] for (int i = 0; i < arraySize; i++) { buffer.put(field.getBytes(rootObj, array, i, true)); } } } else if(field.hasSubCopyBookFields()) { // Complex type fx, Request writeFieldsToBuffer(field.getSubCopyBookFields(), buffer, field.getObject(rootObj)); } else { // Simple type fx. int byte[] bytes = field.getBytes(rootObj, true); if(bytes != null) { buffer.put(bytes); } else if(rootObj == null) {
throw new CopyBookException("Root object for field '" + field.getFieldName() + "' is null and the TypeConverter '" + field.getConverter().getClass().getSimpleName() + "' does not support null filler");
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.POSTFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.POSTFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedDecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateFail() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedDecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateFail() throws Exception {
expectedEx.expect(TypeConverterException.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToBooleanTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBooleanTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToBoolean(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Boolean.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToBooleanTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBooleanTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToBoolean(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Boolean.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteEBCDICBit5Test.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.Charset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteEBCDICBit5Test { private TypeConverter typeConverter; private TypeConverterConfig config; private Charset charset; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.charset = Charset.forName("cp037"); this.config = new TypeConverterConfig(); this.config.setCharset(this.charset); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteEBCDICBit5Test.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.Charset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteEBCDICBit5Test { private TypeConverter typeConverter; private TypeConverterConfig config; private Charset charset; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.charset = Charset.forName("cp037"); this.config = new TypeConverterConfig(); this.config.setCharset(this.charset); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteEBCDICBit5Test.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.Charset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteEBCDICBit5Test { private TypeConverter typeConverter; private TypeConverterConfig config; private Charset charset; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.charset = Charset.forName("cp037"); this.config = new TypeConverterConfig(); this.config.setCharset(this.charset); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteEBCDICBit5Test.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.Charset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteEBCDICBit5Test { private TypeConverter typeConverter; private TypeConverterConfig config; private Charset charset; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.charset = Charset.forName("cp037"); this.config = new TypeConverterConfig(); this.config.setCharset(this.charset); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBook.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookMapper.java // public interface CopyBookMapper { // void initialize(CopyBookSerializerConfig config); // <T> byte[] serialize(T obj); // <T> T deserialize(byte[] bytes, Class<T> type); // int getMaxRecordSize(); // void setMaxRecordSize(int size); // int getMinRecordSize(); // void setMinRecordSize(int size); // }
import com.nordea.oss.copybook.serializers.CopyBookMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface CopyBook {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookMapper.java // public interface CopyBookMapper { // void initialize(CopyBookSerializerConfig config); // <T> byte[] serialize(T obj); // <T> T deserialize(byte[] bytes, Class<T> type); // int getMaxRecordSize(); // void setMaxRecordSize(int size); // int getMinRecordSize(); // void setMinRecordSize(int size); // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBook.java import com.nordea.oss.copybook.serializers.CopyBookMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface CopyBook {
Class<? extends CopyBookMapper> type() default CopyBookMapper.class; // Java sucks and we can use null as default value, so we pick something we would never user here
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTypeExceptionsTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigDecimal;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullTypeExceptionsTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) static public class fieldTypeInteger { @CopyBookLine("01 FIELD PIC 9(2).") public int field; } @CopyBook(type = FullMapper.class) static public class fieldTypeString { @CopyBookLine("01 FIELD PIC X(2).") public String field; } @CopyBook(type = FullMapper.class) static public class fieldTypeDecimal { @CopyBookLine("01 FIELD PIC 9(2)V9(2).") public BigDecimal field; } @org.junit.Test public void testRightFieldTypeInteger() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTypeExceptionsTest.java import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigDecimal; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullTypeExceptionsTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) static public class fieldTypeInteger { @CopyBookLine("01 FIELD PIC 9(2).") public int field; } @CopyBook(type = FullMapper.class) static public class fieldTypeString { @CopyBookLine("01 FIELD PIC X(2).") public String field; } @CopyBook(type = FullMapper.class) static public class fieldTypeDecimal { @CopyBookLine("01 FIELD PIC 9(2)V9(2).") public BigDecimal field; } @org.junit.Test public void testRightFieldTypeInteger() throws Exception {
expectedEx.expect(CopyBookException.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTypeExceptionsTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigDecimal;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullTypeExceptionsTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) static public class fieldTypeInteger { @CopyBookLine("01 FIELD PIC 9(2).") public int field; } @CopyBook(type = FullMapper.class) static public class fieldTypeString { @CopyBookLine("01 FIELD PIC X(2).") public String field; } @CopyBook(type = FullMapper.class) static public class fieldTypeDecimal { @CopyBookLine("01 FIELD PIC 9(2)V9(2).") public BigDecimal field; } @org.junit.Test public void testRightFieldTypeInteger() throws Exception { expectedEx.expect(CopyBookException.class); expectedEx.expectMessage("Field to small for value");
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTypeExceptionsTest.java import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigDecimal; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullTypeExceptionsTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) static public class fieldTypeInteger { @CopyBookLine("01 FIELD PIC 9(2).") public int field; } @CopyBook(type = FullMapper.class) static public class fieldTypeString { @CopyBookLine("01 FIELD PIC X(2).") public String field; } @CopyBook(type = FullMapper.class) static public class fieldTypeDecimal { @CopyBookLine("01 FIELD PIC 9(2)V9(2).") public BigDecimal field; } @org.junit.Test public void testRightFieldTypeInteger() throws Exception { expectedEx.expect(CopyBookException.class); expectedEx.expectMessage("Field to small for value");
CopyBookSerializer serializer = new CopyBookSerializer(fieldTypeInteger.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/DecimalToBigDecimalTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimalTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new DecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateTyopeFail() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/DecimalToBigDecimalTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimalTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new DecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateTyopeFail() throws Exception {
expectedEx.expect(TypeConverterException.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.POSTFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookFullLastArrayShortSerializerTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import java.math.BigDecimal; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertArrayEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookFullLastArrayShortSerializerTest { @CopyBook(type = FullLastArrayShortMapper.class) static public class StringFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC X(4).") public String[] fields; } @org.junit.Test public void testStringFieldOccursTwoTimes() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookFullLastArrayShortSerializerTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import java.math.BigDecimal; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertArrayEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookFullLastArrayShortSerializerTest { @CopyBook(type = FullLastArrayShortMapper.class) static public class StringFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC X(4).") public String[] fields; } @org.junit.Test public void testStringFieldOccursTwoTimes() throws Exception {
CopyBookSerializer serializer = new CopyBookSerializer(StringFieldOccursTwoTimes.class);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) {
if(size > 10 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 10 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 10 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
throw new TypeConverterException("int is not large enough to hold possible value");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 10 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(size > 9 && (this.signingType == CopyBookFieldSigningType.LAST_BYTE_BIT8 || this.signingType == CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5)) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(!(Integer.class.equals(type) || Integer.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToInteger.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import com.nordea.oss.ByteUtils; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 10 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(size > 9 && (this.signingType == CopyBookFieldSigningType.LAST_BYTE_BIT8 || this.signingType == CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5)) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(!(Integer.class.equals(type) || Integer.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToTypeConverterStringEnumTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToTypeConverterStringEnumTest { private TypeConverter typeConverter; private TypeConverterConfig config; public enum TestStringEnum implements TypeConverterStringEnum { HIGH("HH"), MEDIUM("MM"), LOW("LL"); private final String value; TestStringEnum(String value) { this.value = value; } public String getValue() { return value; } } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new StringToTypeConverterStringEnum(); typeConverter.initialize(config); typeConverter.validate(TestStringEnum.class, 2, 1); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(TestStringEnum.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToTypeConverterStringEnumTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToTypeConverterStringEnumTest { private TypeConverter typeConverter; private TypeConverterConfig config; public enum TestStringEnum implements TypeConverterStringEnum { HIGH("HH"), MEDIUM("MM"), LOW("LL"); private final String value; TestStringEnum(String value) { this.value = value; } public String getValue() { return value; } } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new StringToTypeConverterStringEnum(); typeConverter.initialize(config); typeConverter.validate(TestStringEnum.class, 2, 1); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(TestStringEnum.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToLocalDateTime.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToLocalDateTime extends StringToString { DateTimeFormatter formatter; @Override public void initialize(TypeConverterConfig config) { super.initialize(config); this.formatter = DateTimeFormatter.ofPattern(this.format); } @Override public void validate(Class<?> type, int size, int decimals) { if(!(LocalDateTime.class.isAssignableFrom(type))) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToLocalDateTime.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToLocalDateTime extends StringToString { DateTimeFormatter formatter; @Override public void initialize(TypeConverterConfig config) { super.initialize(config); this.formatter = DateTimeFormatter.ofPattern(this.format); } @Override public void validate(Class<?> type, int size, int decimals) { if(!(LocalDateTime.class.isAssignableFrom(type))) {
throw new TypeConverterException("Only supports converting to and from an Enum that is or extends from LocalDateTime");
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToStringTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.*;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToStringTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar(' '); config.setNullFillerChar((char)0); typeConverter = new StringToString(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(String.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToStringTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.*; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToStringTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar(' '); config.setNullFillerChar((char)0); typeConverter = new StringToString(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(String.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimal.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimal extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigDecimal.class.equals(type)) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimal.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimal extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigDecimal.class.equals(type)) {
throw new TypeConverterException("Only supports converting to and from BigDecimal");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimal.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimal extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigDecimal.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigDecimal"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimal.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimal extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigDecimal.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigDecimal"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToTypeConverterStringEnum.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.HashMap; import java.util.Map;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToTypeConverterStringEnum extends StringToString { Class<?> type; Object[] enumConstants; Map<String,Object> toEnumMap = new HashMap<>(); Map<Object,byte[]> fromEnumMap = new HashMap<>(); @Override public void validate(Class<?> type, int size, int decimals) { if(!(TypeConverterStringEnum.class.isAssignableFrom(type))) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToTypeConverterStringEnum.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.HashMap; import java.util.Map; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToTypeConverterStringEnum extends StringToString { Class<?> type; Object[] enumConstants; Map<String,Object> toEnumMap = new HashMap<>(); Map<Object,byte[]> fromEnumMap = new HashMap<>(); @Override public void validate(Class<?> type, int size, int decimals) { if(!(TypeConverterStringEnum.class.isAssignableFrom(type))) {
throw new TypeConverterException("Only supports converting to and from an Enum that implements TypeConverterStringEnum");
NordeaOSS/copybook4java
copybook4java-codegen-maven-plugin/src/main/java/com/nordea/oss/copybook/codegen/CopyBookConverter.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.ByteUtils; import jdk.nashorn.api.scripting.ScriptObjectMirror; import javax.script.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
.collect(Collectors.toList()); } else if (inputFile.isFile()) { inputFiles.add(inputFile); } for(File inFile : inputFiles) { String packageName = inFile.getCanonicalFile().getParent().substring(inputPath.length()).replace('\\', '.').replace('/', '.').replace('_', '.'); packageName = packageName.isEmpty() ? packageRootName : packageRootName + "." + packageName.substring(1); String rootClassName = getClassNameFromFile(inFile); List<String> outClasses = convert(new FileInputStream(inFile), packageName, rootClassName, accessor, charset, subClassHandling, rootClassName); for(String outClass : outClasses) { Matcher classNameMatcher = re_className.matcher(outClass); if (classNameMatcher.find()) { String className = classNameMatcher.group(1); Path outPath = Paths.get(outputPath, packageName.replace('.', '/'),className + ".java"); outPath.getParent().toFile().mkdirs(); System.out.println(" " + outPath); Files.write(outPath, outClass.getBytes(StandardCharsets.UTF_8)); } } } } public List<String> convert(String copybookString, String packageName, String rootClassName, String accessor, String charset, String subClassHandling, String wrapperClassName) throws Exception { ScriptObjectMirror results = (ScriptObjectMirror) invocable.invokeFunction("convertCopybook", packageName, rootClassName, copybookString, accessor, charset, subClassHandling, wrapperClassName); return Arrays.asList(results.values().toArray(new String[results.size()])); } public List<String> convert(InputStream copybookStream, String packageName, String rootClassName, String accessor, String charset, String subClassHandling, String wrapperClassName) throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java-codegen-maven-plugin/src/main/java/com/nordea/oss/copybook/codegen/CopyBookConverter.java import com.nordea.oss.ByteUtils; import jdk.nashorn.api.scripting.ScriptObjectMirror; import javax.script.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; .collect(Collectors.toList()); } else if (inputFile.isFile()) { inputFiles.add(inputFile); } for(File inFile : inputFiles) { String packageName = inFile.getCanonicalFile().getParent().substring(inputPath.length()).replace('\\', '.').replace('/', '.').replace('_', '.'); packageName = packageName.isEmpty() ? packageRootName : packageRootName + "." + packageName.substring(1); String rootClassName = getClassNameFromFile(inFile); List<String> outClasses = convert(new FileInputStream(inFile), packageName, rootClassName, accessor, charset, subClassHandling, rootClassName); for(String outClass : outClasses) { Matcher classNameMatcher = re_className.matcher(outClass); if (classNameMatcher.find()) { String className = classNameMatcher.group(1); Path outPath = Paths.get(outputPath, packageName.replace('.', '/'),className + ".java"); outPath.getParent().toFile().mkdirs(); System.out.println(" " + outPath); Files.write(outPath, outClass.getBytes(StandardCharsets.UTF_8)); } } } } public List<String> convert(String copybookString, String packageName, String rootClassName, String accessor, String charset, String subClassHandling, String wrapperClassName) throws Exception { ScriptObjectMirror results = (ScriptObjectMirror) invocable.invokeFunction("convertCopybook", packageName, rootClassName, copybookString, accessor, charset, subClassHandling, wrapperClassName); return Arrays.asList(results.values().toArray(new String[results.size()])); } public List<String> convert(InputStream copybookStream, String packageName, String rootClassName, String accessor, String charset, String subClassHandling, String wrapperClassName) throws Exception {
return convert(new String(ByteUtils.toByteArray(copybookStream), StandardCharsets.UTF_8), packageName, rootClassName, accessor, charset, subClassHandling, wrapperClassName);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/DecimalToBigDecimal.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimal extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size < 2) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/DecimalToBigDecimal.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimal extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size < 2) {
throw new TypeConverterException("Field to small to hold a decimal number: " + size + " < 2");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/DecimalToBigDecimal.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimal extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size < 2) { throw new TypeConverterException("Field to small to hold a decimal number: " + size + " < 2"); } if(!BigDecimal.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigDecimal"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/DecimalToBigDecimal.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigDecimal; import java.math.BigInteger; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class DecimalToBigDecimal extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(size < 2) { throw new TypeConverterException("Field to small to hold a decimal number: " + size + " < 2"); } if(!BigDecimal.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigDecimal"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler