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
OpsLabJPL/MarsImagesAndroid
MarsImages/Rajawali/src/main/java/rajawali/materials/TextureInfo.java
// Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum CompressionType { // NONE, // ETC1, // PALETTED, // THREEDC, // ATC, // DXT1, // PVRTC // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum FilterType{ // NEAREST, // LINEAR // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum TextureType { // DIFFUSE, // BUMP, // SPECULAR, // ALPHA, // FRAME_BUFFER, // DEPTH_BUFFER, // LOOKUP, // CUBE_MAP, // SPHERE_MAP, // VIDEO_TEXTURE // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum WrapType { // CLAMP, // REPEAT // };
import java.nio.ByteBuffer; import rajawali.materials.TextureManager.CompressionType; import rajawali.materials.TextureManager.FilterType; import rajawali.materials.TextureManager.TextureType; import rajawali.materials.TextureManager.WrapType; import android.graphics.Bitmap; import android.graphics.Bitmap.Config;
package rajawali.materials; /** * This class contains OpenGL specific texture information. * * @author dennis.ippel * */ public class TextureInfo { /** * This texture's unique id */ protected int mTextureId; /** * The type of texture * * @see TextureManager.TextureType */ protected TextureType mTextureType; protected String mTextureName = ""; /** * The shader uniform handle for this texture */ protected int mUniformHandle = -1; /** * Texture width */ protected int mWidth; /** * Texture height */ protected int mHeight; protected Bitmap mTexture; protected Bitmap[] mTextures; protected boolean mMipmap; protected Config mBitmapConfig; protected boolean mShouldRecycle; protected CompressionType mCompressionType; protected int mInternalFormat; protected ByteBuffer[] mBuffer; /** * The type of texture * * @see TextureManager.WrapType */
// Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum CompressionType { // NONE, // ETC1, // PALETTED, // THREEDC, // ATC, // DXT1, // PVRTC // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum FilterType{ // NEAREST, // LINEAR // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum TextureType { // DIFFUSE, // BUMP, // SPECULAR, // ALPHA, // FRAME_BUFFER, // DEPTH_BUFFER, // LOOKUP, // CUBE_MAP, // SPHERE_MAP, // VIDEO_TEXTURE // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum WrapType { // CLAMP, // REPEAT // }; // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureInfo.java import java.nio.ByteBuffer; import rajawali.materials.TextureManager.CompressionType; import rajawali.materials.TextureManager.FilterType; import rajawali.materials.TextureManager.TextureType; import rajawali.materials.TextureManager.WrapType; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; package rajawali.materials; /** * This class contains OpenGL specific texture information. * * @author dennis.ippel * */ public class TextureInfo { /** * This texture's unique id */ protected int mTextureId; /** * The type of texture * * @see TextureManager.TextureType */ protected TextureType mTextureType; protected String mTextureName = ""; /** * The shader uniform handle for this texture */ protected int mUniformHandle = -1; /** * Texture width */ protected int mWidth; /** * Texture height */ protected int mHeight; protected Bitmap mTexture; protected Bitmap[] mTextures; protected boolean mMipmap; protected Config mBitmapConfig; protected boolean mShouldRecycle; protected CompressionType mCompressionType; protected int mInternalFormat; protected ByteBuffer[] mBuffer; /** * The type of texture * * @see TextureManager.WrapType */
protected WrapType mWrapType;
OpsLabJPL/MarsImagesAndroid
MarsImages/Rajawali/src/main/java/rajawali/materials/TextureInfo.java
// Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum CompressionType { // NONE, // ETC1, // PALETTED, // THREEDC, // ATC, // DXT1, // PVRTC // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum FilterType{ // NEAREST, // LINEAR // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum TextureType { // DIFFUSE, // BUMP, // SPECULAR, // ALPHA, // FRAME_BUFFER, // DEPTH_BUFFER, // LOOKUP, // CUBE_MAP, // SPHERE_MAP, // VIDEO_TEXTURE // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum WrapType { // CLAMP, // REPEAT // };
import java.nio.ByteBuffer; import rajawali.materials.TextureManager.CompressionType; import rajawali.materials.TextureManager.FilterType; import rajawali.materials.TextureManager.TextureType; import rajawali.materials.TextureManager.WrapType; import android.graphics.Bitmap; import android.graphics.Bitmap.Config;
package rajawali.materials; /** * This class contains OpenGL specific texture information. * * @author dennis.ippel * */ public class TextureInfo { /** * This texture's unique id */ protected int mTextureId; /** * The type of texture * * @see TextureManager.TextureType */ protected TextureType mTextureType; protected String mTextureName = ""; /** * The shader uniform handle for this texture */ protected int mUniformHandle = -1; /** * Texture width */ protected int mWidth; /** * Texture height */ protected int mHeight; protected Bitmap mTexture; protected Bitmap[] mTextures; protected boolean mMipmap; protected Config mBitmapConfig; protected boolean mShouldRecycle; protected CompressionType mCompressionType; protected int mInternalFormat; protected ByteBuffer[] mBuffer; /** * The type of texture * * @see TextureManager.WrapType */ protected WrapType mWrapType; /** * The type of texture * * @see TextureManager.FilterType */
// Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum CompressionType { // NONE, // ETC1, // PALETTED, // THREEDC, // ATC, // DXT1, // PVRTC // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum FilterType{ // NEAREST, // LINEAR // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum TextureType { // DIFFUSE, // BUMP, // SPECULAR, // ALPHA, // FRAME_BUFFER, // DEPTH_BUFFER, // LOOKUP, // CUBE_MAP, // SPHERE_MAP, // VIDEO_TEXTURE // }; // // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureManager.java // public enum WrapType { // CLAMP, // REPEAT // }; // Path: MarsImages/Rajawali/src/main/java/rajawali/materials/TextureInfo.java import java.nio.ByteBuffer; import rajawali.materials.TextureManager.CompressionType; import rajawali.materials.TextureManager.FilterType; import rajawali.materials.TextureManager.TextureType; import rajawali.materials.TextureManager.WrapType; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; package rajawali.materials; /** * This class contains OpenGL specific texture information. * * @author dennis.ippel * */ public class TextureInfo { /** * This texture's unique id */ protected int mTextureId; /** * The type of texture * * @see TextureManager.TextureType */ protected TextureType mTextureType; protected String mTextureName = ""; /** * The shader uniform handle for this texture */ protected int mUniformHandle = -1; /** * Texture width */ protected int mWidth; /** * Texture height */ protected int mHeight; protected Bitmap mTexture; protected Bitmap[] mTextures; protected boolean mMipmap; protected Config mBitmapConfig; protected boolean mShouldRecycle; protected CompressionType mCompressionType; protected int mInternalFormat; protected ByteBuffer[] mBuffer; /** * The type of texture * * @see TextureManager.WrapType */ protected WrapType mWrapType; /** * The type of texture * * @see TextureManager.FilterType */
protected FilterType mFilterType;
gladclef/banwebplus
scraping/banweb_to_java/src/main/java/scraping/NoCoursesException.java
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // } // // Path: scraping/banweb_to_java/src/main/java/structure/Subject.java // public class Subject implements Comparable<Subject> { // protected String shortName = ""; // protected String longName = ""; // // public Subject(String shortName, String longName) // { // this.shortName = shortName; // this.longName = longName; // } // // /** // * @return The short, computer-friendly version of the subject name. // */ // public String getShortName() // { // return shortName; // } // // /** // * @return The long, human-friendly version of the subjent name. // */ // public String getLongName() // { // return longName; // } // // @Override // public int compareTo(Subject o) { // return longName.compareTo(o.longName); // } // // @Override // public String toString() { // return longName; // } // }
import main.java.structure.Semester; import main.java.structure.Subject;
package main.java.scraping; /** * Indicates that there are no courses found for the registered semester and * subject. */ public class NoCoursesException extends Exception { private static final long serialVersionUID = 4243852685633315992L;
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // } // // Path: scraping/banweb_to_java/src/main/java/structure/Subject.java // public class Subject implements Comparable<Subject> { // protected String shortName = ""; // protected String longName = ""; // // public Subject(String shortName, String longName) // { // this.shortName = shortName; // this.longName = longName; // } // // /** // * @return The short, computer-friendly version of the subject name. // */ // public String getShortName() // { // return shortName; // } // // /** // * @return The long, human-friendly version of the subjent name. // */ // public String getLongName() // { // return longName; // } // // @Override // public int compareTo(Subject o) { // return longName.compareTo(o.longName); // } // // @Override // public String toString() { // return longName; // } // } // Path: scraping/banweb_to_java/src/main/java/scraping/NoCoursesException.java import main.java.structure.Semester; import main.java.structure.Subject; package main.java.scraping; /** * Indicates that there are no courses found for the registered semester and * subject. */ public class NoCoursesException extends Exception { private static final long serialVersionUID = 4243852685633315992L;
public Semester semester;
gladclef/banwebplus
scraping/banweb_to_java/src/main/java/scraping/NoCoursesException.java
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // } // // Path: scraping/banweb_to_java/src/main/java/structure/Subject.java // public class Subject implements Comparable<Subject> { // protected String shortName = ""; // protected String longName = ""; // // public Subject(String shortName, String longName) // { // this.shortName = shortName; // this.longName = longName; // } // // /** // * @return The short, computer-friendly version of the subject name. // */ // public String getShortName() // { // return shortName; // } // // /** // * @return The long, human-friendly version of the subjent name. // */ // public String getLongName() // { // return longName; // } // // @Override // public int compareTo(Subject o) { // return longName.compareTo(o.longName); // } // // @Override // public String toString() { // return longName; // } // }
import main.java.structure.Semester; import main.java.structure.Subject;
package main.java.scraping; /** * Indicates that there are no courses found for the registered semester and * subject. */ public class NoCoursesException extends Exception { private static final long serialVersionUID = 4243852685633315992L; public Semester semester;
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // } // // Path: scraping/banweb_to_java/src/main/java/structure/Subject.java // public class Subject implements Comparable<Subject> { // protected String shortName = ""; // protected String longName = ""; // // public Subject(String shortName, String longName) // { // this.shortName = shortName; // this.longName = longName; // } // // /** // * @return The short, computer-friendly version of the subject name. // */ // public String getShortName() // { // return shortName; // } // // /** // * @return The long, human-friendly version of the subjent name. // */ // public String getLongName() // { // return longName; // } // // @Override // public int compareTo(Subject o) { // return longName.compareTo(o.longName); // } // // @Override // public String toString() { // return longName; // } // } // Path: scraping/banweb_to_java/src/main/java/scraping/NoCoursesException.java import main.java.structure.Semester; import main.java.structure.Subject; package main.java.scraping; /** * Indicates that there are no courses found for the registered semester and * subject. */ public class NoCoursesException extends Exception { private static final long serialVersionUID = 4243852685633315992L; public Semester semester;
public Subject subject;
gladclef/banwebplus
scraping/banweb_to_java/test/structure/SemesterTest.java
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // }
import org.junit.Assert; import org.junit.Test; import main.java.structure.Semester;
package structure; public class SemesterTest { @Test public void getSchoolYear_success() {
// Path: scraping/banweb_to_java/src/main/java/structure/Semester.java // public class Semester implements Comparable<Semester> { // /** Example 201610=Summer,2015 or 201630=Spring,2016 */ // String code = ""; // /** The map of semester indices to names. */ // public static final Map<Integer, String> semesterNames = new HashMap<>(3); // // static { // semesterNames.put(10, "Summer"); // semesterNames.put(20, "Fall"); // semesterNames.put(30, "Spring"); // } // // /** // * @param code // * The banweb-style code for this semester.<br> // * Example "201710" for Summer 2016. // */ // public Semester(String code) { // this.code = code; // } // // /** // * @return The banweb-style code for this semester. // */ // public String getCode() { // return code; // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getSchoolYear() { // return new Integer(code.substring(0, 4)); // } // // /** // * @return The school year this semester is a part of (ending in the // * spring). // */ // public Integer getCalendarYear() { // Integer schoolYear = getSchoolYear(); // if (getSemesterIndex() < 30) { // return schoolYear - 1; // } // return schoolYear; // } // // public String getSemesterName() { // return semesterNames.get(getSemesterIndex()); // } // // /** // * @return 10 for summer, 20 for fall, 30 for spring // */ // public Integer getSemesterIndex() { // return new Integer(code.substring(4, 6)); // } // // /** // * @return What should be the next semester, if the observed pattern // * follows. // */ // public String getPredictedNext() { // Integer semesterIndex = getSemesterIndex(); // if (semesterIndex == 30) { // return (getSchoolYear() + 1) + "" + 10; // } // return getSchoolYear() + "" + (semesterIndex + 10); // } // // @Override // public int compareTo(Semester o) { // Integer mySemester = new Integer(code); // Integer otherSemester = new Integer(o.code); // return mySemester.compareTo(otherSemester); // } // // @Override // public String toString() { // return getSemesterName() + " " + getCalendarYear(); // } // } // Path: scraping/banweb_to_java/test/structure/SemesterTest.java import org.junit.Assert; import org.junit.Test; import main.java.structure.Semester; package structure; public class SemesterTest { @Test public void getSchoolYear_success() {
Assert.assertEquals(new Integer(2016), (new Semester("201610")).getSchoolYear());
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesGeolocationBuilder.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesGeoLocation.java // public class Name { // private String type; // private boolean geohash; // private boolean geohash_prefix; // private int geohash_precision; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public boolean isGeohash() { // return geohash; // } // // public void setGeohash(boolean geohash) { // this.geohash = geohash; // } // // public boolean isGeohash_prefix() { // return geohash_prefix; // } // // public void setGeohash_prefix(boolean geohash_prefix) { // this.geohash_prefix = geohash_prefix; // } // // public int getGeohash_precision() { // return geohash_precision; // } // // public void setGeohash_precision(int geohash_precision) { // this.geohash_precision = geohash_precision; // } // }
import org.nudge.elasticstack.context.elasticsearch.mapping.MappingPropertiesGeoLocation.Properties.Name;
package org.nudge.elasticstack.context.elasticsearch.mapping; /** * * @author Sarah Bourgeois * @author Frederic Massart */ public class MappingPropertiesGeolocationBuilder { public static MappingPropertiesGeoLocation createMappingGeolocationProperties() { MappingPropertiesGeoLocation mpgl = new MappingPropertiesGeoLocation(); MappingPropertiesGeoLocation.Properties properties = mpgl.new Properties(); mpgl.setPropertiesElement(properties);
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesGeoLocation.java // public class Name { // private String type; // private boolean geohash; // private boolean geohash_prefix; // private int geohash_precision; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public boolean isGeohash() { // return geohash; // } // // public void setGeohash(boolean geohash) { // this.geohash = geohash; // } // // public boolean isGeohash_prefix() { // return geohash_prefix; // } // // public void setGeohash_prefix(boolean geohash_prefix) { // this.geohash_prefix = geohash_prefix; // } // // public int getGeohash_precision() { // return geohash_precision; // } // // public void setGeohash_precision(int geohash_precision) { // this.geohash_precision = geohash_precision; // } // } // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesGeolocationBuilder.java import org.nudge.elasticstack.context.elasticsearch.mapping.MappingPropertiesGeoLocation.Properties.Name; package org.nudge.elasticstack.context.elasticsearch.mapping; /** * * @author Sarah Bourgeois * @author Frederic Massart */ public class MappingPropertiesGeolocationBuilder { public static MappingPropertiesGeoLocation createMappingGeolocationProperties() { MappingPropertiesGeoLocation mpgl = new MappingPropertiesGeoLocation(); MappingPropertiesGeoLocation.Properties properties = mpgl.new Properties(); mpgl.setPropertiesElement(properties);
Name name = properties.new Name();
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // }
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL;
package org.nudge.elasticstack.connection; public class ElasticConnection { private static final Logger LOG = Logger.getLogger(ElasticConnection.class.getName()); private final String elasticHost; private final Metadata metadata;
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; package org.nudge.elasticstack.connection; public class ElasticConnection { private static final Logger LOG = Logger.getLogger(ElasticConnection.class.getName()); private final String elasticHost; private final Metadata metadata;
private final ESVersion esVersion;
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // }
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL;
package org.nudge.elasticstack.connection; public class ElasticConnection { private static final Logger LOG = Logger.getLogger(ElasticConnection.class.getName()); private final String elasticHost; private final Metadata metadata; private final ESVersion esVersion; private String esHostIndexURL; public ElasticConnection(String hostUrl) throws Exception { this.elasticHost = hostUrl; String jsonMetadata = get(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.metadata = mapper.readValue(jsonMetadata, Metadata.class); this.esVersion = determineESVersion(this.metadata); } private String get() throws Exception { URL url = new URL(elasticHost); if (LOG.isDebugEnabled()) { LOG.debug("GET " + url); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); String message = readHttpResponse(connection); if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { return message; } else {
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; package org.nudge.elasticstack.connection; public class ElasticConnection { private static final Logger LOG = Logger.getLogger(ElasticConnection.class.getName()); private final String elasticHost; private final Metadata metadata; private final ESVersion esVersion; private String esHostIndexURL; public ElasticConnection(String hostUrl) throws Exception { this.elasticHost = hostUrl; String jsonMetadata = get(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.metadata = mapper.readValue(jsonMetadata, Metadata.class); this.esVersion = determineESVersion(this.metadata); } private String get() throws Exception { URL url = new URL(elasticHost); if (LOG.isDebugEnabled()) { LOG.debug("GET " + url); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); String message = readHttpResponse(connection); if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { return message; } else {
throw new NudgeESConnectorException("Failed ES command with message: " + message);
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // }
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL;
private void checkAndLog(HttpMethod httpMethod, String resource, String body) { if (httpMethod == null || resource == null) { throw new IllegalArgumentException("Cannot request elasticsearch, HttpMethod and resource URL must be provided"); } if (!LOG.isDebugEnabled()) { return; } String requestLog = httpMethod.toString() + " " + resource; if (body != null) { requestLog = requestLog + " with body : \n" + body; } LOG.debug(requestLog); } public void createAndUseIndex(String esIndex) { esHostIndexURL = elasticHost + esIndex + "/"; try { put("", null); } catch (NudgeESConnectorException e) { LOG.info("Index \"" + esIndex + "\" already exists"); } } public ESVersion getEsVersion() { return esVersion; }
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/ESVersion.java // public enum ESVersion { // ES2, ES5, ES6 // } // // Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/exception/UnsupportedElasticStackException.java // @SuppressWarnings("serial") // public class UnsupportedElasticStackException extends RuntimeException { // // public UnsupportedElasticStackException(String message) { // super(message); // } // // public UnsupportedElasticStackException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/nudge/elasticstack/connection/ElasticConnection.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.context.elasticsearch.ESVersion; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.exception.UnsupportedElasticStackException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; private void checkAndLog(HttpMethod httpMethod, String resource, String body) { if (httpMethod == null || resource == null) { throw new IllegalArgumentException("Cannot request elasticsearch, HttpMethod and resource URL must be provided"); } if (!LOG.isDebugEnabled()) { return; } String requestLog = httpMethod.toString() + " " + resource; if (body != null) { requestLog = requestLog + " with body : \n" + body; } LOG.debug(requestLog); } public void createAndUseIndex(String esIndex) { esHostIndexURL = elasticHost + esIndex + "/"; try { put("", null); } catch (NudgeESConnectorException e) { LOG.info("Index \"" + esIndex + "\" already exists"); } } public ESVersion getEsVersion() { return esVersion; }
private ESVersion determineESVersion(Metadata metadata) throws UnsupportedElasticStackException {
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/service/impl/GeoFreeGeoIpImpl.java
// Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/bean/GeoLocation.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class GeoLocation { // // private double latitude; // private double longitude; // private long responseTime; // private String type; // private String transactionId; // // // ===================== // // Getters and Setters // // ===================== // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public double getLatitude() { // return latitude; // } // // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // public double getLongitude() { // return longitude; // } // // public void setLongitude(double longitude) { // this.longitude = longitude; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public String getClientlocation() { // return latitude + "," + longitude; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // // } // // Path: src/main/java/org/nudge/elasticstack/service/GeoLocationService.java // public interface GeoLocationService { // public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException; // }
import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.context.elasticsearch.bean.GeoLocation; import org.nudge.elasticstack.service.GeoLocationService; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
package org.nudge.elasticstack.service.impl; /** * @author Sarah Bourgeois * @author Frederic Massart */ public class GeoFreeGeoIpImpl implements GeoLocationService { private static final Logger LOG = Logger.getLogger(GeoFreeGeoIpImpl.class); private static final String FINAL_URL = "http://freegeoip.net/json/"; @Override
// Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/bean/GeoLocation.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class GeoLocation { // // private double latitude; // private double longitude; // private long responseTime; // private String type; // private String transactionId; // // // ===================== // // Getters and Setters // // ===================== // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public double getLatitude() { // return latitude; // } // // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // public double getLongitude() { // return longitude; // } // // public void setLongitude(double longitude) { // this.longitude = longitude; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public String getClientlocation() { // return latitude + "," + longitude; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // // } // // Path: src/main/java/org/nudge/elasticstack/service/GeoLocationService.java // public interface GeoLocationService { // public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException; // } // Path: src/main/java/org/nudge/elasticstack/service/impl/GeoFreeGeoIpImpl.java import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.context.elasticsearch.bean.GeoLocation; import org.nudge.elasticstack.service.GeoLocationService; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; package org.nudge.elasticstack.service.impl; /** * @author Sarah Bourgeois * @author Frederic Massart */ public class GeoFreeGeoIpImpl implements GeoLocationService { private static final Logger LOG = Logger.getLogger(GeoFreeGeoIpImpl.class); private static final String FINAL_URL = "http://freegeoip.net/json/"; @Override
public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException {
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/service/impl/GeoFreeGeoIpImpl.java
// Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/bean/GeoLocation.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class GeoLocation { // // private double latitude; // private double longitude; // private long responseTime; // private String type; // private String transactionId; // // // ===================== // // Getters and Setters // // ===================== // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public double getLatitude() { // return latitude; // } // // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // public double getLongitude() { // return longitude; // } // // public void setLongitude(double longitude) { // this.longitude = longitude; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public String getClientlocation() { // return latitude + "," + longitude; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // // } // // Path: src/main/java/org/nudge/elasticstack/service/GeoLocationService.java // public interface GeoLocationService { // public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException; // }
import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.context.elasticsearch.bean.GeoLocation; import org.nudge.elasticstack.service.GeoLocationService; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
package org.nudge.elasticstack.service.impl; /** * @author Sarah Bourgeois * @author Frederic Massart */ public class GeoFreeGeoIpImpl implements GeoLocationService { private static final Logger LOG = Logger.getLogger(GeoFreeGeoIpImpl.class); private static final String FINAL_URL = "http://freegeoip.net/json/"; @Override
// Path: src/main/java/org/nudge/elasticstack/exception/NudgeESConnectorException.java // @SuppressWarnings("serial") // public class NudgeESConnectorException extends Exception { // // public NudgeESConnectorException(String m) { // super(m); // } // // public NudgeESConnectorException(String m, Throwable t) { // super(m, t); // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/bean/GeoLocation.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class GeoLocation { // // private double latitude; // private double longitude; // private long responseTime; // private String type; // private String transactionId; // // // ===================== // // Getters and Setters // // ===================== // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public double getLatitude() { // return latitude; // } // // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // public double getLongitude() { // return longitude; // } // // public void setLongitude(double longitude) { // this.longitude = longitude; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public String getClientlocation() { // return latitude + "," + longitude; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // // } // // Path: src/main/java/org/nudge/elasticstack/service/GeoLocationService.java // public interface GeoLocationService { // public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException; // } // Path: src/main/java/org/nudge/elasticstack/service/impl/GeoFreeGeoIpImpl.java import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.log4j.Logger; import org.nudge.elasticstack.exception.NudgeESConnectorException; import org.nudge.elasticstack.context.elasticsearch.bean.GeoLocation; import org.nudge.elasticstack.service.GeoLocationService; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; package org.nudge.elasticstack.service.impl; /** * @author Sarah Bourgeois * @author Frederic Massart */ public class GeoFreeGeoIpImpl implements GeoLocationService { private static final Logger LOG = Logger.getLogger(GeoFreeGeoIpImpl.class); private static final String FINAL_URL = "http://freegeoip.net/json/"; @Override
public GeoLocation requestGeoLocationFromIp(String ip) throws NudgeESConnectorException {
NudgeApm/nudge-elasticstack-connector
src/test/java/org/nudge/elasticstack/context/nudge/rawdata/rawdata/DTOBuilderTest.java
// Path: src/main/java/org/nudge/elasticstack/context/nudge/api/bean/Filter.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Filter { // // public enum Status { // ACTIVE, INACTIVE, DELETED; // // @JsonCreator // public static Status fromString(String key) { // for(Status status : Status.values()) { // if(status.name().equalsIgnoreCase(key)) { // return status; // } // } // return null; // } // } // // private UUID id; // private String name; // @JsonProperty(value = "target_code") // private String targetCode; // private Status status; // // private boolean exclusion; // // private List<Scope> scopes; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTargetCode() { // return targetCode; // } // // public void setTargetCode(String targetCode) { // this.targetCode = targetCode; // } // // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // public boolean isExclusion() { // return exclusion; // } // // public void setExclusion(boolean exclusion) { // this.exclusion = exclusion; // } // // public List<Scope> getScopes() { // return scopes; // } // // public void setScopes(List<Scope> scopes) { // this.scopes = scopes; // } // // @Override // public String toString() { // return "Filter{" + // "id=" + id + // ", name='" + name + '\'' + // ", targetCode='" + targetCode + '\'' + // ", status=" + status + // ", exclusion=" + exclusion + // ", scopes=" + scopes + // '}'; // } // }
import com.nudge.apm.buffer.probe.RawDataProtocol; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.nudge.elasticstack.context.nudge.api.bean.Filter; import org.nudge.elasticstack.context.nudge.dto.*; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package org.nudge.elasticstack.context.nudge.rawdata.rawdata; /** * Test class for {@link DTOBuilder} */ public class DTOBuilderTest { private RawDataProtocol.RawData rawData; /** * Prepare the test by reading a sample example of a Nudge APM rawdata. */ @Before public void init() throws IOException { this.rawData = readRawdata(); } public RawDataProtocol.RawData readRawdata() throws IOException { try { return RawDataProtocol.RawData.parseFrom(this.getClass().getClassLoader() .getResourceAsStream("rawdata/collecte_2016-09-29_10-54-01-620_140.dat")); } catch (IOException e) { throw new IOException("Impossible to read the sample rawdata", e); } } @Test public void buildTransactions() throws Exception {
// Path: src/main/java/org/nudge/elasticstack/context/nudge/api/bean/Filter.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Filter { // // public enum Status { // ACTIVE, INACTIVE, DELETED; // // @JsonCreator // public static Status fromString(String key) { // for(Status status : Status.values()) { // if(status.name().equalsIgnoreCase(key)) { // return status; // } // } // return null; // } // } // // private UUID id; // private String name; // @JsonProperty(value = "target_code") // private String targetCode; // private Status status; // // private boolean exclusion; // // private List<Scope> scopes; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTargetCode() { // return targetCode; // } // // public void setTargetCode(String targetCode) { // this.targetCode = targetCode; // } // // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // public boolean isExclusion() { // return exclusion; // } // // public void setExclusion(boolean exclusion) { // this.exclusion = exclusion; // } // // public List<Scope> getScopes() { // return scopes; // } // // public void setScopes(List<Scope> scopes) { // this.scopes = scopes; // } // // @Override // public String toString() { // return "Filter{" + // "id=" + id + // ", name='" + name + '\'' + // ", targetCode='" + targetCode + '\'' + // ", status=" + status + // ", exclusion=" + exclusion + // ", scopes=" + scopes + // '}'; // } // } // Path: src/test/java/org/nudge/elasticstack/context/nudge/rawdata/rawdata/DTOBuilderTest.java import com.nudge.apm.buffer.probe.RawDataProtocol; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.nudge.elasticstack.context.nudge.api.bean.Filter; import org.nudge.elasticstack.context.nudge.dto.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; package org.nudge.elasticstack.context.nudge.rawdata.rawdata; /** * Test class for {@link DTOBuilder} */ public class DTOBuilderTest { private RawDataProtocol.RawData rawData; /** * Prepare the test by reading a sample example of a Nudge APM rawdata. */ @Before public void init() throws IOException { this.rawData = readRawdata(); } public RawDataProtocol.RawData readRawdata() throws IOException { try { return RawDataProtocol.RawData.parseFrom(this.getClass().getClassLoader() .getResourceAsStream("rawdata/collecte_2016-09-29_10-54-01-620_140.dat")); } catch (IOException e) { throw new IOException("Impossible to read the sample rawdata", e); } } @Test public void buildTransactions() throws Exception {
List<Filter> filters = new ArrayList<>();
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // }
import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute;
package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties);
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute; package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties);
Name name = properties.new Name();
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // }
import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute;
package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties); Name name = properties.new Name(); properties.setName(name);
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute; package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties); Name name = properties.new Name(); properties.setName(name);
Fields fields = name.new Fields();
NudgeApm/nudge-elasticstack-connector
src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // }
import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute;
package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties); Name name = properties.new Name(); properties.setName(name); Fields fields = name.new Fields(); name.setFields(fields);
// Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Name { // private String type; // private Fields fields; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Fields getFields() { // return fields; // } // // public void setFields(Fields fields) { // this.fields = fields; // } // // // ******* Field ******* // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class Fields { // // private FieldAttribute name; // private FieldAttribute raw; // // @JsonProperty("transaction_name") // public FieldAttribute getName() { // return name; // } // // public void setName(FieldAttribute name) { // this.name = name; // } // // public FieldAttribute getRaw() { // return raw; // } // // public void setRaw(FieldAttribute raw) { // this.raw = raw; // } // // // ******* Field Attribute ******* // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // public void setName(String code) { // return; // // } // } // // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingProperties.java // public class FieldAttribute { // private String type; // private String index; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // } // Path: src/main/java/org/nudge/elasticstack/context/elasticsearch/mapping/MappingPropertiesBuilder.java import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields; import org.nudge.elasticstack.context.elasticsearch.mapping.MappingProperties.Properties.Name.Fields.FieldAttribute; package org.nudge.elasticstack.context.elasticsearch.mapping; /** * Build properties to update org.nudge.elasticstack.context.elasticsearch.mapping * * @author : Sarah Bourgeois * @author : Frederic Massart */ public class MappingPropertiesBuilder { public static MappingProperties createMappingProperties() { MappingProperties mappingProperties = new MappingProperties(); MappingProperties.Properties properties = mappingProperties.new Properties(); mappingProperties.setPropertiesElement(properties); Name name = properties.new Name(); properties.setName(name); Fields fields = name.new Fields(); name.setFields(fields);
FieldAttribute nameAttribute = fields.new FieldAttribute();
NudgeApm/nudge-elasticstack-connector
src/test/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializerTest.java
// Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/LayerDTO.java // public class LayerDTO { // // private String layerName; // private long time; // private long count; // private List<LayerCallDTO> calls; // // /*** Getters and Setters ***/ // // public String getLayerName() { // return layerName; // } // // public void setLayerName(String layerName) { // this.layerName = layerName; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getCount() { // return count; // } // // public void setCount(long count) { // this.count = count; // } // // public List<LayerCallDTO> getCalls() { // return calls; // } // // public void setCalls(List<LayerCallDTO> calls) { // this.calls = calls; // } // // /*** Utility methods ***/ // public LayerCallDTO createAddLayerDetail() { // checkLayerDetailList(); // LayerCallDTO layerCall = new LayerCallDTO(); // getCalls().add(layerCall); // return layerCall; // } // // public LayerCallDTO addLayerDetail(LayerCallDTO layerCall) { // if (layerCall == null) { // throw new IllegalArgumentException("The layerCall is invalid, must not be null"); // } // checkLayerDetailList(); // // getCalls().add(layerCall); // return layerCall; // } // // private void checkLayerDetailList() { // if (getCalls() == null) { // setCalls(new ArrayList<LayerCallDTO>()); // } // } // // } // // Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/TransactionDTO.java // public class TransactionDTO { // // private String id; // private String code; // private long startTime; // private long endTime; // private String userIp; // private List<LayerDTO> layers; // // public TransactionDTO() { // this.id = UUID.randomUUID().toString(); // } // // public LayerDTO addNewLayerDTO() { // if (getLayers() == null) { // setLayers(new ArrayList<LayerDTO>()); // } // LayerDTO layerDTO = new LayerDTO(); // getLayers().add(layerDTO); // return layerDTO; // } // // /*** Getters and Setters ***/ // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public String getUserIp() { // return userIp; // } // // public void setUserIp(String userIp) { // this.userIp = userIp; // } // // public List<LayerDTO> getLayers() { // return layers; // } // // public void setLayers(List<LayerDTO> layers) { // this.layers = layers; // } // // }
import org.junit.Test; import org.nudge.elasticstack.context.nudge.dto.LayerDTO; import org.nudge.elasticstack.context.nudge.dto.TransactionDTO; import java.util.ArrayList; import java.util.List;
package org.nudge.elasticstack.context.elasticsearch.builder; public class TransactionSerializerTest { @Test public void test_compute_layers_time() throws Exception { } @Test public void test_build_layers_from_transaction() throws Exception { // given
// Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/LayerDTO.java // public class LayerDTO { // // private String layerName; // private long time; // private long count; // private List<LayerCallDTO> calls; // // /*** Getters and Setters ***/ // // public String getLayerName() { // return layerName; // } // // public void setLayerName(String layerName) { // this.layerName = layerName; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getCount() { // return count; // } // // public void setCount(long count) { // this.count = count; // } // // public List<LayerCallDTO> getCalls() { // return calls; // } // // public void setCalls(List<LayerCallDTO> calls) { // this.calls = calls; // } // // /*** Utility methods ***/ // public LayerCallDTO createAddLayerDetail() { // checkLayerDetailList(); // LayerCallDTO layerCall = new LayerCallDTO(); // getCalls().add(layerCall); // return layerCall; // } // // public LayerCallDTO addLayerDetail(LayerCallDTO layerCall) { // if (layerCall == null) { // throw new IllegalArgumentException("The layerCall is invalid, must not be null"); // } // checkLayerDetailList(); // // getCalls().add(layerCall); // return layerCall; // } // // private void checkLayerDetailList() { // if (getCalls() == null) { // setCalls(new ArrayList<LayerCallDTO>()); // } // } // // } // // Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/TransactionDTO.java // public class TransactionDTO { // // private String id; // private String code; // private long startTime; // private long endTime; // private String userIp; // private List<LayerDTO> layers; // // public TransactionDTO() { // this.id = UUID.randomUUID().toString(); // } // // public LayerDTO addNewLayerDTO() { // if (getLayers() == null) { // setLayers(new ArrayList<LayerDTO>()); // } // LayerDTO layerDTO = new LayerDTO(); // getLayers().add(layerDTO); // return layerDTO; // } // // /*** Getters and Setters ***/ // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public String getUserIp() { // return userIp; // } // // public void setUserIp(String userIp) { // this.userIp = userIp; // } // // public List<LayerDTO> getLayers() { // return layers; // } // // public void setLayers(List<LayerDTO> layers) { // this.layers = layers; // } // // } // Path: src/test/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializerTest.java import org.junit.Test; import org.nudge.elasticstack.context.nudge.dto.LayerDTO; import org.nudge.elasticstack.context.nudge.dto.TransactionDTO; import java.util.ArrayList; import java.util.List; package org.nudge.elasticstack.context.elasticsearch.builder; public class TransactionSerializerTest { @Test public void test_compute_layers_time() throws Exception { } @Test public void test_build_layers_from_transaction() throws Exception { // given
List<TransactionDTO> transactionDTOS = new ArrayList<>();
NudgeApm/nudge-elasticstack-connector
src/test/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializerTest.java
// Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/LayerDTO.java // public class LayerDTO { // // private String layerName; // private long time; // private long count; // private List<LayerCallDTO> calls; // // /*** Getters and Setters ***/ // // public String getLayerName() { // return layerName; // } // // public void setLayerName(String layerName) { // this.layerName = layerName; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getCount() { // return count; // } // // public void setCount(long count) { // this.count = count; // } // // public List<LayerCallDTO> getCalls() { // return calls; // } // // public void setCalls(List<LayerCallDTO> calls) { // this.calls = calls; // } // // /*** Utility methods ***/ // public LayerCallDTO createAddLayerDetail() { // checkLayerDetailList(); // LayerCallDTO layerCall = new LayerCallDTO(); // getCalls().add(layerCall); // return layerCall; // } // // public LayerCallDTO addLayerDetail(LayerCallDTO layerCall) { // if (layerCall == null) { // throw new IllegalArgumentException("The layerCall is invalid, must not be null"); // } // checkLayerDetailList(); // // getCalls().add(layerCall); // return layerCall; // } // // private void checkLayerDetailList() { // if (getCalls() == null) { // setCalls(new ArrayList<LayerCallDTO>()); // } // } // // } // // Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/TransactionDTO.java // public class TransactionDTO { // // private String id; // private String code; // private long startTime; // private long endTime; // private String userIp; // private List<LayerDTO> layers; // // public TransactionDTO() { // this.id = UUID.randomUUID().toString(); // } // // public LayerDTO addNewLayerDTO() { // if (getLayers() == null) { // setLayers(new ArrayList<LayerDTO>()); // } // LayerDTO layerDTO = new LayerDTO(); // getLayers().add(layerDTO); // return layerDTO; // } // // /*** Getters and Setters ***/ // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public String getUserIp() { // return userIp; // } // // public void setUserIp(String userIp) { // this.userIp = userIp; // } // // public List<LayerDTO> getLayers() { // return layers; // } // // public void setLayers(List<LayerDTO> layers) { // this.layers = layers; // } // // }
import org.junit.Test; import org.nudge.elasticstack.context.nudge.dto.LayerDTO; import org.nudge.elasticstack.context.nudge.dto.TransactionDTO; import java.util.ArrayList; import java.util.List;
package org.nudge.elasticstack.context.elasticsearch.builder; public class TransactionSerializerTest { @Test public void test_compute_layers_time() throws Exception { } @Test public void test_build_layers_from_transaction() throws Exception { // given List<TransactionDTO> transactionDTOS = new ArrayList<>(); TransactionDTO transactionDTO = new TransactionDTO();
// Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/LayerDTO.java // public class LayerDTO { // // private String layerName; // private long time; // private long count; // private List<LayerCallDTO> calls; // // /*** Getters and Setters ***/ // // public String getLayerName() { // return layerName; // } // // public void setLayerName(String layerName) { // this.layerName = layerName; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getCount() { // return count; // } // // public void setCount(long count) { // this.count = count; // } // // public List<LayerCallDTO> getCalls() { // return calls; // } // // public void setCalls(List<LayerCallDTO> calls) { // this.calls = calls; // } // // /*** Utility methods ***/ // public LayerCallDTO createAddLayerDetail() { // checkLayerDetailList(); // LayerCallDTO layerCall = new LayerCallDTO(); // getCalls().add(layerCall); // return layerCall; // } // // public LayerCallDTO addLayerDetail(LayerCallDTO layerCall) { // if (layerCall == null) { // throw new IllegalArgumentException("The layerCall is invalid, must not be null"); // } // checkLayerDetailList(); // // getCalls().add(layerCall); // return layerCall; // } // // private void checkLayerDetailList() { // if (getCalls() == null) { // setCalls(new ArrayList<LayerCallDTO>()); // } // } // // } // // Path: src/main/java/org/nudge/elasticstack/context/nudge/dto/TransactionDTO.java // public class TransactionDTO { // // private String id; // private String code; // private long startTime; // private long endTime; // private String userIp; // private List<LayerDTO> layers; // // public TransactionDTO() { // this.id = UUID.randomUUID().toString(); // } // // public LayerDTO addNewLayerDTO() { // if (getLayers() == null) { // setLayers(new ArrayList<LayerDTO>()); // } // LayerDTO layerDTO = new LayerDTO(); // getLayers().add(layerDTO); // return layerDTO; // } // // /*** Getters and Setters ***/ // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public String getUserIp() { // return userIp; // } // // public void setUserIp(String userIp) { // this.userIp = userIp; // } // // public List<LayerDTO> getLayers() { // return layers; // } // // public void setLayers(List<LayerDTO> layers) { // this.layers = layers; // } // // } // Path: src/test/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializerTest.java import org.junit.Test; import org.nudge.elasticstack.context.nudge.dto.LayerDTO; import org.nudge.elasticstack.context.nudge.dto.TransactionDTO; import java.util.ArrayList; import java.util.List; package org.nudge.elasticstack.context.elasticsearch.builder; public class TransactionSerializerTest { @Test public void test_compute_layers_time() throws Exception { } @Test public void test_build_layers_from_transaction() throws Exception { // given List<TransactionDTO> transactionDTOS = new ArrayList<>(); TransactionDTO transactionDTO = new TransactionDTO();
List<LayerDTO> layerDTOS = new ArrayList<>();
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/ApiParams.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import java.lang.reflect.Type; import com.sailthru.client.ApiAction;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public interface ApiParams { public Type getType();
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/ApiParams.java import java.lang.reflect.Type; import com.sailthru.client.ApiAction; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public interface ApiParams { public Type getType();
public ApiAction getApiCall();
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Send.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map;
} public Send setScheduleTime(Object startTime, Object endTime) { Map<String, Object> scheduleTime = new LinkedHashMap<String, Object>(); if (startTime instanceof String || startTime instanceof Number) { scheduleTime.put("start_time", startTime); } if (endTime instanceof String || endTime instanceof Number) { scheduleTime.put("end_time", endTime); } this.schedule_time = scheduleTime; return this; } public Type getType() { Type type = new TypeToken<Send>() {}.getType(); return type; } public Send setBehalfEmail(String email) { this.options.put("behalf_email", email); return this; } public Send setOptions(Map<String, Object> options) { this.options = options; return this; } @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Send.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; } public Send setScheduleTime(Object startTime, Object endTime) { Map<String, Object> scheduleTime = new LinkedHashMap<String, Object>(); if (startTime instanceof String || startTime instanceof Number) { scheduleTime.put("start_time", startTime); } if (endTime instanceof String || endTime instanceof Number) { scheduleTime.put("end_time", endTime); } this.schedule_time = scheduleTime; return this; } public Type getType() { Type type = new TypeToken<Send>() {}.getType(); return type; } public Send setBehalfEmail(String email) { this.options.put("behalf_email", email); return this; } public Send setOptions(Map<String, Object> options) { this.options = options; return this; } @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
examples/com/sailthru/client/UserExample.java
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/params/User.java // public class User extends AbstractApiParams implements ApiParams { // public static final String PARAM_TEMPLATE = "user"; // // protected String id; // protected String key; // protected Map<String, Object> fields; // protected Map<String, String> keys; // protected String keysconflict; // protected Map<String, Object> vars; // protected Map<String, Integer> lists; // protected String optout_email; // protected String optout_sms_status; // protected Map<String, Object> login; // // public User(String id) { // this.id = id; // } // // public User() { // // this will be used when new user_id is to be created // } // // public User setKey(String key) { // this.key = key; // return this; // } // // public User setFields(Map<String, Object> fields) { // this.fields = fields; // return this; // } // // public User setKeys(Map<String, String> keys) { // this.keys = keys; // return this; // } // // public User setKeysConflict(String keysConflict) { // this.keysconflict = keysConflict; // return this; // } // // public User setVars(Map<String, Object> vars) { // this.vars = vars; // return this; // } // // public User setLists(Map<String, Integer> lists) { // this.lists = lists; // return this; // } // // public User setOptoutEmail(String optoutEmail) { // this.optout_email = optoutEmail; // return this; // } // // public User setOptoutSmsStatus(String optoutSmsStatus) { // this.optout_sms_status = optoutSmsStatus; // return this; // } // // public User setLogin(Map<String, Object> login) { // this.login = login; // return this; // } // // public Type getType() { // java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); // return _type; // } // // public ApiAction getApiCall() { // return ApiAction.user; // } // }
import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.User; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map;
package com.sailthru.client; public class UserExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { String sailthruId = "4d371896cc0c1adbb079b8d0";
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/params/User.java // public class User extends AbstractApiParams implements ApiParams { // public static final String PARAM_TEMPLATE = "user"; // // protected String id; // protected String key; // protected Map<String, Object> fields; // protected Map<String, String> keys; // protected String keysconflict; // protected Map<String, Object> vars; // protected Map<String, Integer> lists; // protected String optout_email; // protected String optout_sms_status; // protected Map<String, Object> login; // // public User(String id) { // this.id = id; // } // // public User() { // // this will be used when new user_id is to be created // } // // public User setKey(String key) { // this.key = key; // return this; // } // // public User setFields(Map<String, Object> fields) { // this.fields = fields; // return this; // } // // public User setKeys(Map<String, String> keys) { // this.keys = keys; // return this; // } // // public User setKeysConflict(String keysConflict) { // this.keysconflict = keysConflict; // return this; // } // // public User setVars(Map<String, Object> vars) { // this.vars = vars; // return this; // } // // public User setLists(Map<String, Integer> lists) { // this.lists = lists; // return this; // } // // public User setOptoutEmail(String optoutEmail) { // this.optout_email = optoutEmail; // return this; // } // // public User setOptoutSmsStatus(String optoutSmsStatus) { // this.optout_sms_status = optoutSmsStatus; // return this; // } // // public User setLogin(Map<String, Object> login) { // this.login = login; // return this; // } // // public Type getType() { // java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); // return _type; // } // // public ApiAction getApiCall() { // return ApiAction.user; // } // } // Path: examples/com/sailthru/client/UserExample.java import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.User; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; package com.sailthru.client; public class UserExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { String sailthruId = "4d371896cc0c1adbb079b8d0";
User user = new User(sailthruId);
sailthru/sailthru-java-client
examples/com/sailthru/client/UserExample.java
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/params/User.java // public class User extends AbstractApiParams implements ApiParams { // public static final String PARAM_TEMPLATE = "user"; // // protected String id; // protected String key; // protected Map<String, Object> fields; // protected Map<String, String> keys; // protected String keysconflict; // protected Map<String, Object> vars; // protected Map<String, Integer> lists; // protected String optout_email; // protected String optout_sms_status; // protected Map<String, Object> login; // // public User(String id) { // this.id = id; // } // // public User() { // // this will be used when new user_id is to be created // } // // public User setKey(String key) { // this.key = key; // return this; // } // // public User setFields(Map<String, Object> fields) { // this.fields = fields; // return this; // } // // public User setKeys(Map<String, String> keys) { // this.keys = keys; // return this; // } // // public User setKeysConflict(String keysConflict) { // this.keysconflict = keysConflict; // return this; // } // // public User setVars(Map<String, Object> vars) { // this.vars = vars; // return this; // } // // public User setLists(Map<String, Integer> lists) { // this.lists = lists; // return this; // } // // public User setOptoutEmail(String optoutEmail) { // this.optout_email = optoutEmail; // return this; // } // // public User setOptoutSmsStatus(String optoutSmsStatus) { // this.optout_sms_status = optoutSmsStatus; // return this; // } // // public User setLogin(Map<String, Object> login) { // this.login = login; // return this; // } // // public Type getType() { // java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); // return _type; // } // // public ApiAction getApiCall() { // return ApiAction.user; // } // }
import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.User; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map;
package com.sailthru.client; public class UserExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { String sailthruId = "4d371896cc0c1adbb079b8d0"; User user = new User(sailthruId); Map<String, Object> vars = new HashMap<String, Object>(); vars.put("name", "Prajwal Tuladhar"); Map<String, String> addressVars = new HashMap<String, String>(); addressVars.put("state", "NY"); addressVars.put("city", "Jackson Heights"); addressVars.put("zip", "11372"); vars.put("address", addressVars); user.setVars(vars); JsonResponse response1 = client.getUser(user); // GET JsonResponse response2 = client.saveUser(user); if (response1.isOK()) { System.out.println(response1.getResponse()); } else { System.out.println(response1.getResponse().get("error").toString()); } // optionally get the rate limit information for the corresponding API endpoint/method LastRateLimitInfo lastRateLimitInfo = client.getLastRateLimitInfo(ApiAction.user, AbstractSailthruClient.HttpRequestMethod.POST); if (lastRateLimitInfo != null) { // examine rate limit information int limit = lastRateLimitInfo.getLimit(); int remaining = lastRateLimitInfo.getRemaining(); Date reset = lastRateLimitInfo.getReset(); // ... }
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/params/User.java // public class User extends AbstractApiParams implements ApiParams { // public static final String PARAM_TEMPLATE = "user"; // // protected String id; // protected String key; // protected Map<String, Object> fields; // protected Map<String, String> keys; // protected String keysconflict; // protected Map<String, Object> vars; // protected Map<String, Integer> lists; // protected String optout_email; // protected String optout_sms_status; // protected Map<String, Object> login; // // public User(String id) { // this.id = id; // } // // public User() { // // this will be used when new user_id is to be created // } // // public User setKey(String key) { // this.key = key; // return this; // } // // public User setFields(Map<String, Object> fields) { // this.fields = fields; // return this; // } // // public User setKeys(Map<String, String> keys) { // this.keys = keys; // return this; // } // // public User setKeysConflict(String keysConflict) { // this.keysconflict = keysConflict; // return this; // } // // public User setVars(Map<String, Object> vars) { // this.vars = vars; // return this; // } // // public User setLists(Map<String, Integer> lists) { // this.lists = lists; // return this; // } // // public User setOptoutEmail(String optoutEmail) { // this.optout_email = optoutEmail; // return this; // } // // public User setOptoutSmsStatus(String optoutSmsStatus) { // this.optout_sms_status = optoutSmsStatus; // return this; // } // // public User setLogin(Map<String, Object> login) { // this.login = login; // return this; // } // // public Type getType() { // java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); // return _type; // } // // public ApiAction getApiCall() { // return ApiAction.user; // } // } // Path: examples/com/sailthru/client/UserExample.java import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.User; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; package com.sailthru.client; public class UserExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { String sailthruId = "4d371896cc0c1adbb079b8d0"; User user = new User(sailthruId); Map<String, Object> vars = new HashMap<String, Object>(); vars.put("name", "Prajwal Tuladhar"); Map<String, String> addressVars = new HashMap<String, String>(); addressVars.put("state", "NY"); addressVars.put("city", "Jackson Heights"); addressVars.put("zip", "11372"); vars.put("address", addressVars); user.setVars(vars); JsonResponse response1 = client.getUser(user); // GET JsonResponse response2 = client.saveUser(user); if (response1.isOK()) { System.out.println(response1.getResponse()); } else { System.out.println(response1.getResponse().get("error").toString()); } // optionally get the rate limit information for the corresponding API endpoint/method LastRateLimitInfo lastRateLimitInfo = client.getLastRateLimitInfo(ApiAction.user, AbstractSailthruClient.HttpRequestMethod.POST); if (lastRateLimitInfo != null) { // examine rate limit information int limit = lastRateLimitInfo.getLimit(); int remaining = lastRateLimitInfo.getRemaining(); Date reset = lastRateLimitInfo.getReset(); // ... }
} catch (ApiException e) {
sailthru/sailthru-java-client
src/main/com/sailthru/client/http/SailthruHandler.java
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // }
import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST:
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // Path: src/main/com/sailthru/client/http/SailthruHandler.java import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST:
throw ApiException.create(statusLine, parseObject);
sailthru/sailthru-java-client
src/main/com/sailthru/client/http/SailthruHandler.java
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // }
import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST: throw ApiException.create(statusLine, parseObject); case STATUS_UNAUTHORIZED:
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // Path: src/main/com/sailthru/client/http/SailthruHandler.java import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST: throw ApiException.create(statusLine, parseObject); case STATUS_UNAUTHORIZED:
throw UnAuthorizedException.create(statusLine, parseObject);
sailthru/sailthru-java-client
src/main/com/sailthru/client/http/SailthruHandler.java
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // }
import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST: throw ApiException.create(statusLine, parseObject); case STATUS_UNAUTHORIZED: throw UnAuthorizedException.create(statusLine, parseObject); case STATUS_FORBIDDEN: throw ApiException.create(statusLine, parseObject); case STATUS_NOT_FOUND:
// Path: src/main/com/sailthru/client/LastRateLimitInfo.java // public class LastRateLimitInfo { // /** // * The value of X-Rate-Limit-Limit, representing the limit of requests/minute for this action / method combination // */ // private final int limit; // // /** // * The value of X-Rate-Limit-Remaining, representing how many requests remain in the current minute // */ // private final int remaining; // // /** // * The value of X-rate-Limit-Reset, representing the UNIX epoch timestamp of when the next minute starts, and when the rate limit resets // */ // private final Date reset; // // public LastRateLimitInfo(int limit, int remaining, Date reset) { // this.limit = limit; // this.remaining = remaining; // this.reset = reset; // } // // public int getLimit() { // return limit; // } // // public int getRemaining() { // return remaining; // } // // public Date getReset() { // return reset; // } // } // // Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/ResourceNotFoundException.java // public class ResourceNotFoundException extends ApiException { // public ResourceNotFoundException(int statusCode, String reason, // Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // // Path: src/main/com/sailthru/client/exceptions/UnAuthorizedException.java // public class UnAuthorizedException extends ApiException { // public UnAuthorizedException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(statusCode, reason, jsonResponse); // } // } // Path: src/main/com/sailthru/client/http/SailthruHandler.java import com.sailthru.client.LastRateLimitInfo; import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.exceptions.ResourceNotFoundException; import com.sailthru.client.exceptions.UnAuthorizedException; import com.sailthru.client.handler.SailthruResponseHandler; import java.io.IOException; import java.util.Date; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.sailthru.client.http; /** * * @author Prajwal Tuladhar <[email protected]> */ public class SailthruHandler implements ResponseHandler<Object> { private SailthruResponseHandler handler; private static final Logger logger = LoggerFactory.getLogger(SailthruHandler.class); // key used to store rate limit info, for use and removal by the parent SailthruClient public static final String RATE_LIMIT_INFO_KEY = "x_rate_limit_info"; /* Supported HTTP Status codes */ public static final int STATUS_OK = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_FORBIDDEN = 403; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_METHOD_NOT_FOUND = 405; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public SailthruHandler(SailthruResponseHandler handler) { super(); this.handler = handler; } public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { logger.debug("Received Response: {}", httpResponse.toString()); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String jsonString = null; jsonString = EntityUtils.toString(httpResponse.getEntity()); Object parseObject = handler.parseResponse(jsonString); addRateLimitInfoToResponseObject(httpResponse, parseObject); switch (statusCode) { case STATUS_OK: break; case STATUS_BAD_REQUEST: throw ApiException.create(statusLine, parseObject); case STATUS_UNAUTHORIZED: throw UnAuthorizedException.create(statusLine, parseObject); case STATUS_FORBIDDEN: throw ApiException.create(statusLine, parseObject); case STATUS_NOT_FOUND:
throw ResourceNotFoundException.create(statusLine, parseObject);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/job/ImportJob.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/params/ApiFileParams.java // public interface ApiFileParams { // Map<String, Object> getFileParams(); // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import com.sailthru.client.params.ApiFileParams; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.List; import java.util.Map; import java.lang.reflect.Type; import java.util.HashMap;
package com.sailthru.client.params.job; public class ImportJob extends Job implements ApiFileParams { private static final String JOB = "import"; protected String emails; protected transient File file = null; protected transient InputStream fileInputStream = null; protected String list; public ImportJob() { this.job = JOB; } public ImportJob setEmails(List<String> emails) {
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/params/ApiFileParams.java // public interface ApiFileParams { // Map<String, Object> getFileParams(); // } // Path: src/main/com/sailthru/client/params/job/ImportJob.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import com.sailthru.client.params.ApiFileParams; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.List; import java.util.Map; import java.lang.reflect.Type; import java.util.HashMap; package com.sailthru.client.params.job; public class ImportJob extends Job implements ApiFileParams { private static final String JOB = "import"; protected String emails; protected transient File file = null; protected transient InputStream fileInputStream = null; protected String list; public ImportJob() { this.job = JOB; } public ImportJob setEmails(List<String> emails) {
this.emails = SailthruUtil.arrayListToCSV(emails);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Event.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Map;
public Event() { // this will be used when new user_id is to be created } public Event setKey(String key) { this.key = key; return this; } public Event setEvent(String eventName) { this.event = eventName; return this; } public Event setVars(Map<String, Object> vars) { this.vars = vars; return this; } public Event setScheduleTime(String scheduleTime) { this.schedule_time = scheduleTime; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<Event>() {}.getType(); return _type; }
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Event.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Map; public Event() { // this will be used when new user_id is to be created } public Event setKey(String key) { this.key = key; return this; } public Event setEvent(String eventName) { this.event = eventName; return this; } public Event setVars(Map<String, Object> vars) { this.vars = vars; return this; } public Event setScheduleTime(String scheduleTime) { this.schedule_time = scheduleTime; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<Event>() {}.getType(); return _type; }
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Email.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
} public Email setSend(String template) { this.send = template; return this; } public Email setSendVars(Map<String, Object> sendVars) { this.send_vars = sendVars; return this; } @SuppressWarnings("unchecked") public Email setVars(Map<String, Object> vars) { this.vars = vars; return this; } public Email setTextOnly() { this.vars.put("text_only", 1); return this; } public Type getType() { Type type = new TypeToken<Email>() {}.getType(); return type; } @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Email.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; } public Email setSend(String template) { this.send = template; return this; } public Email setSendVars(Map<String, Object> sendVars) { this.send_vars = sendVars; return this; } @SuppressWarnings("unchecked") public Email setVars(Map<String, Object> vars) { this.vars = vars; return this; } public Email setTextOnly() { this.vars.put("text_only", 1); return this; } public Type getType() { Type type = new TypeToken<Email>() {}.getType(); return type; } @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/MultiSend.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class MultiSend extends Send { protected Map<String, Object> evars; public MultiSend() { this.options = new HashMap<String, Object>(); } public MultiSend setEmails(java.util.List<String> emails) {
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // Path: src/main/com/sailthru/client/params/MultiSend.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class MultiSend extends Send { protected Map<String, Object> evars; public MultiSend() { this.options = new HashMap<String, Object>(); } public MultiSend setEmails(java.util.List<String> emails) {
this.email = SailthruUtil.arrayListToCSV(emails);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/AbstractApiParams.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/handler/JsonHandler.java // public class JsonHandler implements SailthruResponseHandler { // // public static final String format = "json"; // // // public Object parseResponse(String response) { // GsonBuilder builder = new GsonBuilder(); // builder.setDateFormat(SailthruUtil.SAILTHRU_API_DATE_FORMAT); // builder.registerTypeAdapter(Object.class, new NaturalDeserializer()); // Gson gson = builder.create(); // return gson.fromJson(response, Object.class); // } // // // public String getFormat() { // return format; // } // // // http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java/4799594#4799594 // //Will get rid of this at some point // class NaturalDeserializer implements JsonDeserializer<Object> { // // public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { // if (json.isJsonNull()) { // return null; // } // else if (json.isJsonPrimitive()) { // return handlePrimitive(json.getAsJsonPrimitive()); // } // else if (json.isJsonArray()) { // return handleArray(json.getAsJsonArray(), context); // } // else { // return handleObject(json.getAsJsonObject(), context); // } // } // // private Object handlePrimitive(JsonPrimitive json) { // if (json.isString()) { // return json.getAsString(); // } // else if (json.isBoolean()) { // return json.getAsBoolean(); // } // else { // BigDecimal bigDec = json.getAsBigDecimal(); // // Find out if it is an int type // try { // bigDec.toBigIntegerExact(); // try { // return bigDec.intValueExact(); // } // catch (ArithmeticException e) {} // return bigDec.longValue(); // } // catch (ArithmeticException e) {} // return bigDec.doubleValue(); // } // } // // private Object handleArray(JsonArray json, JsonDeserializationContext context) { // Object[] array = new Object[json.size()]; // for (int i = 0; i < array.length; i++) { // if (json.get(i).isJsonObject()) { // array[i] = handleObject((JsonObject)json.get(i), context); // } // else { // array[i] = context.deserialize(json.get(i), Object.class); // } // } // return array; // } // // private Object handleObject(JsonObject json, JsonDeserializationContext context) { // Map<String, Object> map = new HashMap<String, Object>(); // for (Map.Entry<String, JsonElement> entry : json.entrySet()) { // map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)); // } // return map; // } // } // }
import com.google.gson.Gson; import com.sailthru.client.SailthruUtil; import com.sailthru.client.handler.JsonHandler; import java.util.HashMap; import java.util.Map;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public abstract class AbstractApiParams { public Map<String, Object> toHashMap() {
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/handler/JsonHandler.java // public class JsonHandler implements SailthruResponseHandler { // // public static final String format = "json"; // // // public Object parseResponse(String response) { // GsonBuilder builder = new GsonBuilder(); // builder.setDateFormat(SailthruUtil.SAILTHRU_API_DATE_FORMAT); // builder.registerTypeAdapter(Object.class, new NaturalDeserializer()); // Gson gson = builder.create(); // return gson.fromJson(response, Object.class); // } // // // public String getFormat() { // return format; // } // // // http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java/4799594#4799594 // //Will get rid of this at some point // class NaturalDeserializer implements JsonDeserializer<Object> { // // public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { // if (json.isJsonNull()) { // return null; // } // else if (json.isJsonPrimitive()) { // return handlePrimitive(json.getAsJsonPrimitive()); // } // else if (json.isJsonArray()) { // return handleArray(json.getAsJsonArray(), context); // } // else { // return handleObject(json.getAsJsonObject(), context); // } // } // // private Object handlePrimitive(JsonPrimitive json) { // if (json.isString()) { // return json.getAsString(); // } // else if (json.isBoolean()) { // return json.getAsBoolean(); // } // else { // BigDecimal bigDec = json.getAsBigDecimal(); // // Find out if it is an int type // try { // bigDec.toBigIntegerExact(); // try { // return bigDec.intValueExact(); // } // catch (ArithmeticException e) {} // return bigDec.longValue(); // } // catch (ArithmeticException e) {} // return bigDec.doubleValue(); // } // } // // private Object handleArray(JsonArray json, JsonDeserializationContext context) { // Object[] array = new Object[json.size()]; // for (int i = 0; i < array.length; i++) { // if (json.get(i).isJsonObject()) { // array[i] = handleObject((JsonObject)json.get(i), context); // } // else { // array[i] = context.deserialize(json.get(i), Object.class); // } // } // return array; // } // // private Object handleObject(JsonObject json, JsonDeserializationContext context) { // Map<String, Object> map = new HashMap<String, Object>(); // for (Map.Entry<String, JsonElement> entry : json.entrySet()) { // map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)); // } // return map; // } // } // } // Path: src/main/com/sailthru/client/params/AbstractApiParams.java import com.google.gson.Gson; import com.sailthru.client.SailthruUtil; import com.sailthru.client.handler.JsonHandler; import java.util.HashMap; import java.util.Map; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public abstract class AbstractApiParams { public Map<String, Object> toHashMap() {
Gson gson = SailthruUtil.createGson();
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/AbstractApiParams.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/handler/JsonHandler.java // public class JsonHandler implements SailthruResponseHandler { // // public static final String format = "json"; // // // public Object parseResponse(String response) { // GsonBuilder builder = new GsonBuilder(); // builder.setDateFormat(SailthruUtil.SAILTHRU_API_DATE_FORMAT); // builder.registerTypeAdapter(Object.class, new NaturalDeserializer()); // Gson gson = builder.create(); // return gson.fromJson(response, Object.class); // } // // // public String getFormat() { // return format; // } // // // http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java/4799594#4799594 // //Will get rid of this at some point // class NaturalDeserializer implements JsonDeserializer<Object> { // // public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { // if (json.isJsonNull()) { // return null; // } // else if (json.isJsonPrimitive()) { // return handlePrimitive(json.getAsJsonPrimitive()); // } // else if (json.isJsonArray()) { // return handleArray(json.getAsJsonArray(), context); // } // else { // return handleObject(json.getAsJsonObject(), context); // } // } // // private Object handlePrimitive(JsonPrimitive json) { // if (json.isString()) { // return json.getAsString(); // } // else if (json.isBoolean()) { // return json.getAsBoolean(); // } // else { // BigDecimal bigDec = json.getAsBigDecimal(); // // Find out if it is an int type // try { // bigDec.toBigIntegerExact(); // try { // return bigDec.intValueExact(); // } // catch (ArithmeticException e) {} // return bigDec.longValue(); // } // catch (ArithmeticException e) {} // return bigDec.doubleValue(); // } // } // // private Object handleArray(JsonArray json, JsonDeserializationContext context) { // Object[] array = new Object[json.size()]; // for (int i = 0; i < array.length; i++) { // if (json.get(i).isJsonObject()) { // array[i] = handleObject((JsonObject)json.get(i), context); // } // else { // array[i] = context.deserialize(json.get(i), Object.class); // } // } // return array; // } // // private Object handleObject(JsonObject json, JsonDeserializationContext context) { // Map<String, Object> map = new HashMap<String, Object>(); // for (Map.Entry<String, JsonElement> entry : json.entrySet()) { // map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)); // } // return map; // } // } // }
import com.google.gson.Gson; import com.sailthru.client.SailthruUtil; import com.sailthru.client.handler.JsonHandler; import java.util.HashMap; import java.util.Map;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public abstract class AbstractApiParams { public Map<String, Object> toHashMap() { Gson gson = SailthruUtil.createGson(); String json = gson.toJson(this);
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/handler/JsonHandler.java // public class JsonHandler implements SailthruResponseHandler { // // public static final String format = "json"; // // // public Object parseResponse(String response) { // GsonBuilder builder = new GsonBuilder(); // builder.setDateFormat(SailthruUtil.SAILTHRU_API_DATE_FORMAT); // builder.registerTypeAdapter(Object.class, new NaturalDeserializer()); // Gson gson = builder.create(); // return gson.fromJson(response, Object.class); // } // // // public String getFormat() { // return format; // } // // // http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java/4799594#4799594 // //Will get rid of this at some point // class NaturalDeserializer implements JsonDeserializer<Object> { // // public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { // if (json.isJsonNull()) { // return null; // } // else if (json.isJsonPrimitive()) { // return handlePrimitive(json.getAsJsonPrimitive()); // } // else if (json.isJsonArray()) { // return handleArray(json.getAsJsonArray(), context); // } // else { // return handleObject(json.getAsJsonObject(), context); // } // } // // private Object handlePrimitive(JsonPrimitive json) { // if (json.isString()) { // return json.getAsString(); // } // else if (json.isBoolean()) { // return json.getAsBoolean(); // } // else { // BigDecimal bigDec = json.getAsBigDecimal(); // // Find out if it is an int type // try { // bigDec.toBigIntegerExact(); // try { // return bigDec.intValueExact(); // } // catch (ArithmeticException e) {} // return bigDec.longValue(); // } // catch (ArithmeticException e) {} // return bigDec.doubleValue(); // } // } // // private Object handleArray(JsonArray json, JsonDeserializationContext context) { // Object[] array = new Object[json.size()]; // for (int i = 0; i < array.length; i++) { // if (json.get(i).isJsonObject()) { // array[i] = handleObject((JsonObject)json.get(i), context); // } // else { // array[i] = context.deserialize(json.get(i), Object.class); // } // } // return array; // } // // private Object handleObject(JsonObject json, JsonDeserializationContext context) { // Map<String, Object> map = new HashMap<String, Object>(); // for (Map.Entry<String, JsonElement> entry : json.entrySet()) { // map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)); // } // return map; // } // } // } // Path: src/main/com/sailthru/client/params/AbstractApiParams.java import com.google.gson.Gson; import com.sailthru.client.SailthruUtil; import com.sailthru.client.handler.JsonHandler; import java.util.HashMap; import java.util.Map; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public abstract class AbstractApiParams { public Map<String, Object> toHashMap() { Gson gson = SailthruUtil.createGson(); String json = gson.toJson(this);
JsonHandler handler = new JsonHandler();
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Blast.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.Map;
this.test_percent = percentage; return this; } public Blast setDataFeedUrl(String dataFeedUrl) { this.data_feed_url = dataFeedUrl; return this; } public Blast setDataFeedUrl(URI dataFeedUrl) { this.data_feed_url = dataFeedUrl.toString(); return this; } public Blast setSetup(String setup) { this.setup = setup; return this; } public Blast setVars(Map<String, Object> vars){ this.vars = vars; return this; } public Type getType() { Type type = new TypeToken<Blast>() {}.getType(); return type; } @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Blast.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.Map; this.test_percent = percentage; return this; } public Blast setDataFeedUrl(String dataFeedUrl) { this.data_feed_url = dataFeedUrl; return this; } public Blast setDataFeedUrl(URI dataFeedUrl) { this.data_feed_url = dataFeedUrl.toString(); return this; } public Blast setSetup(String setup) { this.setup = setup; return this; } public Blast setVars(Map<String, Object> vars){ this.vars = vars; return this; } public Type getType() { Type type = new TypeToken<Blast>() {}.getType(); return type; } @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Alert.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.util.List; import java.util.Map; import java.lang.reflect.Type;
this.min = min; return this; } public Alert setMaxQuery(Map<String, Number> max) { this.max = max; return this; } public Alert setTagsQuery(List<String> tags) { this.tags = tags; return this; } public Alert setType(TypeMode mode) { this.type = mode.toString(); return this; } public Alert setWhen(String when) { this.when = when; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<Alert>() {}.getType(); return _type; } @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Alert.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.util.List; import java.util.Map; import java.lang.reflect.Type; this.min = min; return this; } public Alert setMaxQuery(Map<String, Number> max) { this.max = max; return this; } public Alert setTagsQuery(List<String> tags) { this.tags = tags; return this; } public Alert setType(TypeMode mode) { this.type = mode.toString(); return this; } public Alert setWhen(String when) { this.when = when; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<Alert>() {}.getType(); return _type; } @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/job/UpdateJob.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/params/ApiFileParams.java // public interface ApiFileParams { // Map<String, Object> getFileParams(); // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import com.sailthru.client.params.ApiFileParams; import com.sailthru.client.params.query.Query; import java.io.File; import java.lang.reflect.Type; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.sailthru.client.params.job; public class UpdateJob extends Job implements ApiFileParams { private static final String JOB = "update"; protected String emails; protected String url; protected transient File file; protected Map<String, Object> update; protected Map<String, Object> query; public UpdateJob() { this.job = JOB; this.update = new HashMap<String, Object>(); } public UpdateJob setEmails(List<String> emails) {
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // // Path: src/main/com/sailthru/client/params/ApiFileParams.java // public interface ApiFileParams { // Map<String, Object> getFileParams(); // } // Path: src/main/com/sailthru/client/params/job/UpdateJob.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.SailthruUtil; import com.sailthru.client.params.ApiFileParams; import com.sailthru.client.params.query.Query; import java.io.File; import java.lang.reflect.Type; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; package com.sailthru.client.params.job; public class UpdateJob extends Job implements ApiFileParams { private static final String JOB = "update"; protected String emails; protected String url; protected transient File file; protected Map<String, Object> update; protected Map<String, Object> query; public UpdateJob() { this.job = JOB; this.update = new HashMap<String, Object>(); } public UpdateJob setEmails(List<String> emails) {
this.emails = SailthruUtil.arrayListToCSV(emails);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/job/Job.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/params/AbstractApiParams.java // public abstract class AbstractApiParams { // public Map<String, Object> toHashMap() { // Gson gson = SailthruUtil.createGson(); // String json = gson.toJson(this); // JsonHandler handler = new JsonHandler(); // return (Map<String, Object>)handler.parseResponse(json); // } // // } // // Path: src/main/com/sailthru/client/params/ApiParams.java // public interface ApiParams { // public Type getType(); // // public ApiAction getApiCall(); // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.params.AbstractApiParams; import com.sailthru.client.params.ApiParams; import java.lang.reflect.Type;
package com.sailthru.client.params.job; /** * * @author Prajwal Tuladhar <[email protected]> */ abstract public class Job extends AbstractApiParams implements ApiParams { protected String job_id; protected String job; protected String report_email; protected String postback_url; public static final String JOB_ID = "job_id"; public Type getType() { return new TypeToken<Job>() {}.getType(); } public Job setReportEmail(String reportEmail) { this.report_email = reportEmail; return this; } public Job setPostbackUrl(String postbackUrl) { this.postback_url = postbackUrl; return this; } public Job setJob(String job) { this.job = job; return this; }
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/params/AbstractApiParams.java // public abstract class AbstractApiParams { // public Map<String, Object> toHashMap() { // Gson gson = SailthruUtil.createGson(); // String json = gson.toJson(this); // JsonHandler handler = new JsonHandler(); // return (Map<String, Object>)handler.parseResponse(json); // } // // } // // Path: src/main/com/sailthru/client/params/ApiParams.java // public interface ApiParams { // public Type getType(); // // public ApiAction getApiCall(); // } // Path: src/main/com/sailthru/client/params/job/Job.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.params.AbstractApiParams; import com.sailthru.client.params.ApiParams; import java.lang.reflect.Type; package com.sailthru.client.params.job; /** * * @author Prajwal Tuladhar <[email protected]> */ abstract public class Job extends AbstractApiParams implements ApiParams { protected String job_id; protected String job; protected String report_email; protected String postback_url; public static final String JOB_ID = "job_id"; public Type getType() { return new TypeToken<Job>() {}.getType(); } public Job setReportEmail(String reportEmail) { this.report_email = reportEmail; return this; } public Job setPostbackUrl(String postbackUrl) { this.postback_url = postbackUrl; return this; } public Job setJob(String job) { this.job = job; return this; }
public ApiAction getApiCall() {
sailthru/sailthru-java-client
examples/com/sailthru/client/TemplateExample.java
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // }
import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.Template; import java.io.IOException; import java.util.Date;
package com.sailthru.client; public class TemplateExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { Template template = new Template(); template.setTemplate("my-template"); template.setFromEmail("[email protected]"); template.setFromName("Example Example"); template.setSubject("Hello {name}!"); template.setContentHtml("HTML content goes here"); template.setContentText("Text content goes here"); JsonResponse response = client.saveTemplate(template); if (response.isOK()) { System.out.println(response.getResponse()); } else { System.out.println(response.getResponse().get("error").toString()); } // optionally get the rate limit information for the corresponding API endpoint/method LastRateLimitInfo lastRateLimitInfo = client.getLastRateLimitInfo(ApiAction.template, AbstractSailthruClient.HttpRequestMethod.POST); if (lastRateLimitInfo != null) { // examine rate limit information int limit = lastRateLimitInfo.getLimit(); int remaining = lastRateLimitInfo.getRemaining(); Date reset = lastRateLimitInfo.getReset(); // ... }
// Path: src/main/com/sailthru/client/exceptions/ApiException.java // @SuppressWarnings("serial") // public class ApiException extends IOException { // // private static final String ERRORMSG = "errormsg"; // // private static final Logger logger = LoggerFactory.getLogger(ApiException.class); // // private Map<String, Object> jsonResponse; // private int statusCode; // // public ApiException(int statusCode, String reason, Map<String, Object> jsonResponse) { // super(reason); // logger.warn("{}: {}", statusCode, reason); // this.jsonResponse = jsonResponse; // this.statusCode = statusCode; // } // // public Map<String, Object> getResponse() { // return jsonResponse; // } // // public int getStatusCode() { // return statusCode; // } // // @SuppressWarnings("unchecked") // public static ApiException create(StatusLine statusLine, Object jsonResponse) { // return create(statusLine, (Map<String, Object>)jsonResponse); // } // // public static ApiException create(StatusLine statusLine, Map<String, Object> jsonResponse) { // if (jsonResponse == null) { // jsonResponse = new HashMap<String, Object>(); // } // // final String errorMessage = jsonResponse.get(ERRORMSG) == null ? "" : // jsonResponse.get(ERRORMSG).toString(); // // return new ApiException(statusLine.getStatusCode(), errorMessage, jsonResponse); // } // } // Path: examples/com/sailthru/client/TemplateExample.java import com.sailthru.client.exceptions.ApiException; import com.sailthru.client.handler.response.JsonResponse; import com.sailthru.client.params.Template; import java.io.IOException; import java.util.Date; package com.sailthru.client; public class TemplateExample { public static void main(String[] args) { String apiKey = "****"; String apiSecret = "****"; SailthruClient client = new SailthruClient(apiKey, apiSecret); try { Template template = new Template(); template.setTemplate("my-template"); template.setFromEmail("[email protected]"); template.setFromName("Example Example"); template.setSubject("Hello {name}!"); template.setContentHtml("HTML content goes here"); template.setContentText("Text content goes here"); JsonResponse response = client.saveTemplate(template); if (response.isOK()) { System.out.println(response.getResponse()); } else { System.out.println(response.getResponse().get("error").toString()); } // optionally get the rate limit information for the corresponding API endpoint/method LastRateLimitInfo lastRateLimitInfo = client.getLastRateLimitInfo(ApiAction.template, AbstractSailthruClient.HttpRequestMethod.POST); if (lastRateLimitInfo != null) { // examine rate limit information int limit = lastRateLimitInfo.getLimit(); int remaining = lastRateLimitInfo.getRemaining(); Date reset = lastRateLimitInfo.getReset(); // ... }
} catch (ApiException e) {
sailthru/sailthru-java-client
src/main/com/sailthru/client/handler/JsonHandler.java
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map;
package com.sailthru.client.handler; /** * handles JSON response from server * * @author Prajwal Tuladhar <[email protected]> */ public class JsonHandler implements SailthruResponseHandler { public static final String format = "json"; public Object parseResponse(String response) { GsonBuilder builder = new GsonBuilder();
// Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // Path: src/main/com/sailthru/client/handler/JsonHandler.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; package com.sailthru.client.handler; /** * handles JSON response from server * * @author Prajwal Tuladhar <[email protected]> */ public class JsonHandler implements SailthruResponseHandler { public static final String format = "json"; public Object parseResponse(String response) { GsonBuilder builder = new GsonBuilder();
builder.setDateFormat(SailthruUtil.SAILTHRU_API_DATE_FORMAT);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/User.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Map;
public User setVars(Map<String, Object> vars) { this.vars = vars; return this; } public User setLists(Map<String, Integer> lists) { this.lists = lists; return this; } public User setOptoutEmail(String optoutEmail) { this.optout_email = optoutEmail; return this; } public User setOptoutSmsStatus(String optoutSmsStatus) { this.optout_sms_status = optoutSmsStatus; return this; } public User setLogin(Map<String, Object> login) { this.login = login; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); return _type; }
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/User.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.Map; public User setVars(Map<String, Object> vars) { this.vars = vars; return this; } public User setLists(Map<String, Integer> lists) { this.lists = lists; return this; } public User setOptoutEmail(String optoutEmail) { this.optout_email = optoutEmail; return this; } public User setOptoutSmsStatus(String optoutSmsStatus) { this.optout_sms_status = optoutSmsStatus; return this; } public User setLogin(Map<String, Object> login) { this.login = login; return this; } public Type getType() { java.lang.reflect.Type _type = new TypeToken<User>() {}.getType(); return _type; }
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Content.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import java.util.List; import java.util.ArrayList;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class Content extends AbstractApiParams implements ApiParams { // required protected String url; // optional protected String title; protected String date; protected String expire_date; protected List<String> tags; protected Map<String, Object> vars; protected Map<String, String> keys; protected Map<String, Map<String, String>> images; protected List<Double> location; protected Long price; protected String description; protected String site_name; protected String author; protected Integer spider; @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // Path: src/main/com/sailthru/client/params/Content.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import java.util.List; import java.util.ArrayList; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class Content extends AbstractApiParams implements ApiParams { // required protected String url; // optional protected String title; protected String date; protected String expire_date; protected List<String> tags; protected Map<String, Object> vars; protected Map<String, String> keys; protected Map<String, Map<String, String>> images; protected List<Double> location; protected Long price; protected String description; protected String site_name; protected String author; protected Integer spider; @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Content.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // }
import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import java.util.List; import java.util.ArrayList;
public Content setSpecialVars(ContentSpecialVar var, String value) { switch (var) { case PRICE: this.vars.put("price", value); break; case DESCRIPTION: this.vars.put("description", value); break; case BRAND: this.vars.put("brand", value); break; } return this; } /* * A map of image names to { “url” : <url> } image maps. * Use the name “full” to denote the full-sized image, and “thumb” to denote * the thumbnail-sized image. Other image names are not reserved. * Or use setFullImage and setThumbImage to set them separately. */ public Content setImages(Map<String, Map<String, String>> images) { this.images = images; return this; } public Content setFullImage(String url) {
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // // Path: src/main/com/sailthru/client/SailthruUtil.java // public class SailthruUtil { // // public static final String SAILTHRU_API_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; // // /** // * generates MD5 Hash // * @param data parameter data // * @return MD5 hashed string // */ // public static String md5(String data) { // try { // return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { // return DigestUtils.md5Hex(data.toString()); // } // } // // /** // * Converts String ArrayList to CSV string // * @param list List of String to create a CSV string // * @return CSV string // */ // public static String arrayListToCSV(List<String> list) { // StringBuilder csv = new StringBuilder(); // for (String str : list) { // csv.append(str); // csv.append(","); // } // int lastIndex = csv.length() - 1; // char last = csv.charAt(lastIndex); // if (last == ',') { // return csv.substring(0, lastIndex); // } // return csv.toString(); // } // // public static Gson createGson() { // return new GsonBuilder().setDateFormat(SAILTHRU_API_DATE_FORMAT) // .registerTypeHierarchyAdapter(Map.class, new NullSerializingMapTypeAdapter()) // .create(); // } // // /** // * Add a new image entry to the images map. // * // * @param images map containing the references of images. Can be null, in that case the returned map will be a new instance with the entry // * @param key key for the map, either "full" or "thumb" // * @param url url for the image to use // * @return a new map instance of the images parameter was null otherwise the updated map. // */ // public static Map<String, Map<String, String>> putImage(Map<String, Map<String, String>> images, String key, String url) { // if (images == null) { // images = new HashMap<String, Map<String, String>>(); // } // Map<String, String> urlMap = new HashMap<String, String>(); // urlMap.put("url", url); // images.put(key, urlMap); // return images; // } // // } // Path: src/main/com/sailthru/client/params/Content.java import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import com.sailthru.client.SailthruUtil; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import java.util.List; import java.util.ArrayList; public Content setSpecialVars(ContentSpecialVar var, String value) { switch (var) { case PRICE: this.vars.put("price", value); break; case DESCRIPTION: this.vars.put("description", value); break; case BRAND: this.vars.put("brand", value); break; } return this; } /* * A map of image names to { “url” : <url> } image maps. * Use the name “full” to denote the full-sized image, and “thumb” to denote * the thumbnail-sized image. Other image names are not reserved. * Or use setFullImage and setThumbImage to set them separately. */ public Content setImages(Map<String, Map<String, String>> images) { this.images = images; return this; } public Content setFullImage(String url) {
this.images = SailthruUtil.putImage(this.images, "full", url);
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/Purchase.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map;
} public String getAppId() { return appId; } public Purchase setAppId(String appId) { this.appId = appId; return this; } public String getDeviceId() { return deviceId; } public Purchase setDeviceId(String deviceId) { this.deviceId = deviceId; return this; } public String getUserAgent() { return userAgent; } public Purchase setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } @Override
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/Purchase.java import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.sailthru.client.ApiAction; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; } public String getAppId() { return appId; } public Purchase setAppId(String appId) { this.appId = appId; return this; } public String getDeviceId() { return deviceId; } public Purchase setDeviceId(String deviceId) { this.deviceId = deviceId; return this; } public String getUserAgent() { return userAgent; } public Purchase setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } @Override
public ApiAction getApiCall() {
sailthru/sailthru-java-client
src/main/com/sailthru/client/params/List.java
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // }
import com.sailthru.client.ApiAction; import com.google.gson.reflect.TypeToken; import com.sailthru.client.params.query.Query; import java.lang.reflect.Type; import java.util.ArrayList;
package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class List extends AbstractApiParams implements ApiParams { protected String list; protected Integer primary; protected ListType type; protected Query query; public List setQuery(Query query) { this.query = query; return this; } public List setList(String list) { this.list = list; return this; } public List setPrimary() { this.primary = 1; return this; } public List setListType(ListType listType) { this.type = listType; return this; }
// Path: src/main/com/sailthru/client/ApiAction.java // public enum ApiAction { // event, // settings, // email, // send, // blast, // blast_repeat, // preview, // template, // list, // content, // alert, // stats, // purchase, // horizon, // job, // trigger, // inbox, // user, // RETURN, // the case is inconsistent, but "return" is a reserved keyword // content_watch { public String toString() { return "content/watch"; } }, // content_watch_profile { public String toString() { return "content/watch/profile"; } }, // } // Path: src/main/com/sailthru/client/params/List.java import com.sailthru.client.ApiAction; import com.google.gson.reflect.TypeToken; import com.sailthru.client.params.query.Query; import java.lang.reflect.Type; import java.util.ArrayList; package com.sailthru.client.params; /** * * @author Prajwal Tuladhar <[email protected]> */ public class List extends AbstractApiParams implements ApiParams { protected String list; protected Integer primary; protected ListType type; protected Query query; public List setQuery(Query query) { this.query = query; return this; } public List setList(String list) { this.list = list; return this; } public List setPrimary() { this.primary = 1; return this; } public List setListType(ListType listType) { this.type = listType; return this; }
public ApiAction getApiCall() {
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-client/src/main/java/it/test/client/E2E.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // }
import it.test.model.FieldVerifier; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel;
sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText();
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // Path: src/it/e2e/e2e-client/src/main/java/it/test/client/E2E.java import it.test.model.FieldVerifier; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
tbroyer/gwt-maven-plugin
src/it/gwt-lib/src/test/java/it/testlib/GwtSuite.java
// Path: src/it/gwt-lib/src/test/java/it/testlib/client/LibTest.java // public class LibTest extends GWTTestCase { // @Override // public String getModuleName() { // return "it.testlib.TestLib"; // } // // public void testShouldRun() { // GWT.log("Hello world!"); // } // // public void testSuperSource() { // assertTrue(SuperSourced.isSuperSourced()); // } // // public void testProcessed() { // assertEquals("foo", Processed.create("foo").getProperty()); // assertEquals("bar", Processed2.create("bar").getProperty()); // } // }
import it.testlib.client.LibTest; import com.google.gwt.junit.tools.GWTTestSuite; import junit.framework.Test;
package it.testlib; public class GwtSuite { public static Test suite() { GWTTestSuite suite = new GWTTestSuite("Test suite for lib");
// Path: src/it/gwt-lib/src/test/java/it/testlib/client/LibTest.java // public class LibTest extends GWTTestCase { // @Override // public String getModuleName() { // return "it.testlib.TestLib"; // } // // public void testShouldRun() { // GWT.log("Hello world!"); // } // // public void testSuperSource() { // assertTrue(SuperSourced.isSuperSourced()); // } // // public void testProcessed() { // assertEquals("foo", Processed.create("foo").getProperty()); // assertEquals("bar", Processed2.create("bar").getProperty()); // } // } // Path: src/it/gwt-lib/src/test/java/it/testlib/GwtSuite.java import it.testlib.client.LibTest; import com.google.gwt.junit.tools.GWTTestSuite; import junit.framework.Test; package it.testlib; public class GwtSuite { public static Test suite() { GWTTestSuite suite = new GWTTestSuite("Test suite for lib");
suite.addTestSuite(LibTest.class);
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // }
import it.test.model.GreetingResponse; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
package it.test.shared; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService {
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java import it.test.model.GreetingResponse; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; package it.test.shared; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService {
GreetingResponse greetServer(String name) throws IllegalArgumentException;
tbroyer/gwt-maven-plugin
src/it/gwt-app/src/test/java/it/test/GwtSuite.java
// Path: src/it/gwt-app/src/test/java/it/test/client/AppTest.java // public class AppTest extends GWTTestCase { // @Override // public String getModuleName() { // return "it.test.Test"; // } // // public void testShouldRun() { // GWT.log("Hello world!"); // } // // public void testSuperSource() { // assertTrue(SuperSourced.isSuperSourced()); // } // // public void testProcessed() { // assertEquals("foo", Processed.create("foo").getProperty()); // assertEquals("bar", Processed2.create("bar").getProperty()); // } // }
import it.test.client.AppTest; import com.google.gwt.junit.tools.GWTTestSuite; import junit.framework.Test;
package it.test; public class GwtSuite { public static Test suite() { GWTTestSuite suite = new GWTTestSuite("Test suite for app");
// Path: src/it/gwt-app/src/test/java/it/test/client/AppTest.java // public class AppTest extends GWTTestCase { // @Override // public String getModuleName() { // return "it.test.Test"; // } // // public void testShouldRun() { // GWT.log("Hello world!"); // } // // public void testSuperSource() { // assertTrue(SuperSourced.isSuperSourced()); // } // // public void testProcessed() { // assertEquals("foo", Processed.create("foo").getProperty()); // assertEquals("bar", Processed2.create("bar").getProperty()); // } // } // Path: src/it/gwt-app/src/test/java/it/test/GwtSuite.java import it.test.client.AppTest; import com.google.gwt.junit.tools.GWTTestSuite; import junit.framework.Test; package it.test; public class GwtSuite { public static Test suite() { GWTTestSuite suite = new GWTTestSuite("Test suite for app");
suite.addTestSuite(AppTest.class);
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-client/src/main/java/it/test/client/Greeter.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // // Path: src/it/e2e/e2e-shared-gwt/src/main/java/it/test/shared/GreetingServiceAsync.java // public interface GreetingServiceAsync { // void greetServer(String input, AsyncCallback<GreetingResponse> callback) // throws IllegalArgumentException; // }
import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import it.test.shared.GreetingServiceAsync; import com.google.auto.value.AutoValue; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Callback; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.rpc.AsyncCallback;
package it.test.client; /** * This is a contrived example to use an annotation processor (AutoValue), * to test generated sources. */ class Greeter { /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // // Path: src/it/e2e/e2e-shared-gwt/src/main/java/it/test/shared/GreetingServiceAsync.java // public interface GreetingServiceAsync { // void greetServer(String input, AsyncCallback<GreetingResponse> callback) // throws IllegalArgumentException; // } // Path: src/it/e2e/e2e-client/src/main/java/it/test/client/Greeter.java import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import it.test.shared.GreetingServiceAsync; import com.google.auto.value.AutoValue; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Callback; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.rpc.AsyncCallback; package it.test.client; /** * This is a contrived example to use an annotation processor (AutoValue), * to test generated sources. */ class Greeter { /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-client/src/main/java/it/test/client/Greeter.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // // Path: src/it/e2e/e2e-shared-gwt/src/main/java/it/test/shared/GreetingServiceAsync.java // public interface GreetingServiceAsync { // void greetServer(String input, AsyncCallback<GreetingResponse> callback) // throws IllegalArgumentException; // }
import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import it.test.shared.GreetingServiceAsync; import com.google.auto.value.AutoValue; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Callback; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.rpc.AsyncCallback;
package it.test.client; /** * This is a contrived example to use an annotation processor (AutoValue), * to test generated sources. */ class Greeter { /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT .create(GreetingService.class); void greet(String name, final Callback<Result, Throwable> callback) { greetingService.greetServer(name,
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // // Path: src/it/e2e/e2e-shared-gwt/src/main/java/it/test/shared/GreetingServiceAsync.java // public interface GreetingServiceAsync { // void greetServer(String input, AsyncCallback<GreetingResponse> callback) // throws IllegalArgumentException; // } // Path: src/it/e2e/e2e-client/src/main/java/it/test/client/Greeter.java import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import it.test.shared.GreetingServiceAsync; import com.google.auto.value.AutoValue; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Callback; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.rpc.AsyncCallback; package it.test.client; /** * This is a contrived example to use an annotation processor (AutoValue), * to test generated sources. */ class Greeter { /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT .create(GreetingService.class); void greet(String name, final Callback<Result, Throwable> callback) { greetingService.greetServer(name,
new AsyncCallback<GreetingResponse>() {
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // }
import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // Path: src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // }
import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // Path: src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
public GreetingResponse greetServer(String input) throws IllegalArgumentException {
tbroyer/gwt-maven-plugin
src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // }
import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public GreetingResponse greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid.
// Path: src/it/e2e/e2e-model/src/main/java/it/test/model/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // // Path: src/it/e2e/e2e-model/src/main/java/it/test/model/GreetingResponse.java // @SuppressWarnings("serial") // @AutoValue // @GwtCompatible(serializable = true) // public abstract class GreetingResponse { // public static Builder builder() { // return new AutoValue_GreetingResponse.Builder(); // } // // public abstract String getGreeting(); // // public abstract String getServerInfo(); // // public abstract String getUserAgent(); // // @AutoValue.Builder // public static abstract class Builder { // public abstract Builder setGreeting(String greeting); // // public abstract Builder setServerInfo(String serverInfo); // // public abstract Builder setUserAgent(String userAgent); // // public abstract GreetingResponse build(); // } // } // // Path: src/it/e2e/e2e-shared/src/main/java/it/test/shared/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // GreetingResponse greetServer(String name) throws IllegalArgumentException; // } // Path: src/it/e2e/e2e-server/src/main/java/it/test/server/GreetingServiceImpl.java import it.test.model.FieldVerifier; import it.test.model.GreetingResponse; import it.test.shared.GreetingService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; package it.test.server; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public GreetingResponse greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid.
if (!FieldVerifier.isValidName(input)) {
robovm/robovm-idea
src/main/java/org/robovm/idea/builder/RoboVmTemplatesFactory.java
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // }
import com.intellij.ide.util.projectWizard.JavaModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.platform.templates.BuilderBasedTemplate; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.robovm.idea.RoboVmIcons; import javax.swing.*;
/* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.builder; /** * Returns a project template for every template known * by the templater. If a user selects one of the templates * it's build with the {@link RoboVmModuleBuilder} * */ public class RoboVmTemplatesFactory extends ProjectTemplatesFactory { @NotNull @Override public String[] getGroups() { return new String[] { "RoboVM" }; } @Override public int getGroupWeight(String group) { return JavaModuleBuilder.JAVA_MOBILE_WEIGHT; } @Override public String getParentGroup(String group) { return "Java"; } @Override public Icon getGroupIcon(String group) {
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // } // Path: src/main/java/org/robovm/idea/builder/RoboVmTemplatesFactory.java import com.intellij.ide.util.projectWizard.JavaModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.platform.templates.BuilderBasedTemplate; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.robovm.idea.RoboVmIcons; import javax.swing.*; /* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.builder; /** * Returns a project template for every template known * by the templater. If a user selects one of the templates * it's build with the {@link RoboVmModuleBuilder} * */ public class RoboVmTemplatesFactory extends ProjectTemplatesFactory { @NotNull @Override public String[] getGroups() { return new String[] { "RoboVM" }; } @Override public int getGroupWeight(String group) { return JavaModuleBuilder.JAVA_MOBILE_WEIGHT; } @Override public String getParentGroup(String group) { return "Java"; } @Override public Icon getGroupIcon(String group) {
return RoboVmIcons.ROBOVM_SMALL;
robovm/robovm-idea
src/main/java/org/robovm/idea/running/RoboVmIOSConfigurationType.java
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // }
import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import org.jetbrains.annotations.NotNull; import org.robovm.idea.RoboVmIcons; import javax.swing.*;
/* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.running; public class RoboVmIOSConfigurationType implements ConfigurationType { @Override public String getDisplayName() { return "RoboVM iOS"; } @Override public String getConfigurationTypeDescription() { return "A run configuration to test your app on the iOS simulator or an iOS device"; } @Override public Icon getIcon() {
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // } // Path: src/main/java/org/robovm/idea/running/RoboVmIOSConfigurationType.java import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import org.jetbrains.annotations.NotNull; import org.robovm.idea.RoboVmIcons; import javax.swing.*; /* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.running; public class RoboVmIOSConfigurationType implements ConfigurationType { @Override public String getDisplayName() { return "RoboVM iOS"; } @Override public String getConfigurationTypeDescription() { return "A run configuration to test your app on the iOS simulator or an iOS device"; } @Override public Icon getIcon() {
return RoboVmIcons.ROBOVM_SMALL;
robovm/robovm-idea
src/main/java/org/robovm/idea/interfacebuilder/StoryboardFileTypeFactory.java
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // }
import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.robovm.idea.RoboVmIcons; import javax.swing.*;
/* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.interfacebuilder; /** * Created by badlogic on 08/04/15. */ public class StoryboardFileTypeFactory extends FileTypeFactory { public static class StoryboardFileType implements FileType { public static final StoryboardFileType INSTANCE = new StoryboardFileType(); @NotNull @Override public String getName() { return "iOS Storyboard"; } @NotNull @Override public String getDescription() { return "An iOS Storyboard file"; } @NotNull @Override public String getDefaultExtension() { return "storyboard"; } @Nullable @Override public Icon getIcon() {
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // } // Path: src/main/java/org/robovm/idea/interfacebuilder/StoryboardFileTypeFactory.java import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.robovm.idea.RoboVmIcons; import javax.swing.*; /* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.interfacebuilder; /** * Created by badlogic on 08/04/15. */ public class StoryboardFileTypeFactory extends FileTypeFactory { public static class StoryboardFileType implements FileType { public static final StoryboardFileType INSTANCE = new StoryboardFileType(); @NotNull @Override public String getName() { return "iOS Storyboard"; } @NotNull @Override public String getDescription() { return "An iOS Storyboard file"; } @NotNull @Override public String getDefaultExtension() { return "storyboard"; } @Nullable @Override public Icon getIcon() {
return RoboVmIcons.ROBOVM_SMALL;
robovm/robovm-idea
src/main/java/org/robovm/idea/running/RoboVmConsoleConfigurationType.java
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // }
import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import org.jetbrains.annotations.NotNull; import org.robovm.idea.RoboVmIcons; import javax.swing.*;
/* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.running; /** * Created by badlogic on 25/03/15. */ public class RoboVmConsoleConfigurationType implements ConfigurationType { @Override public String getDisplayName() { return "RoboVM Console"; } @Override public String getConfigurationTypeDescription() { return "A run configuration to test your console app"; } @Override public Icon getIcon() {
// Path: src/main/java/org/robovm/idea/RoboVmIcons.java // public class RoboVmIcons { // public static final Icon ROBOVM_SMALL = IconLoader.findIcon("/icons/robovm_small.png"); // public static final Icon ROBOVM_LARGE = IconLoader.findIcon("/icons/robovm_large.png"); // } // Path: src/main/java/org/robovm/idea/running/RoboVmConsoleConfigurationType.java import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import org.jetbrains.annotations.NotNull; import org.robovm.idea.RoboVmIcons; import javax.swing.*; /* * Copyright (C) 2015 RoboVM AB * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package org.robovm.idea.running; /** * Created by badlogic on 25/03/15. */ public class RoboVmConsoleConfigurationType implements ConfigurationType { @Override public String getDisplayName() { return "RoboVM Console"; } @Override public String getConfigurationTypeDescription() { return "A run configuration to test your console app"; } @Override public Icon getIcon() {
return RoboVmIcons.ROBOVM_SMALL;
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/domain/api/GetTokenInteractor.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // }
import com.mangopay.android.sdk.model.exception.MangoException;
package com.mangopay.android.sdk.domain.api; public interface GetTokenInteractor { interface Callback { void onGetTokenSuccess(String response);
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/domain/api/GetTokenInteractor.java import com.mangopay.android.sdk.model.exception.MangoException; package com.mangopay.android.sdk.domain.api; public interface GetTokenInteractor { interface Callback { void onGetTokenSuccess(String response);
void onGetTokenError(MangoException error);
Mangopay/cardregistration-android-kit
mangopay/src/test/java/com.mangopay.android.sdk/model/MangoCardTest.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // }
import com.mangopay.android.sdk.model.exception.MangoException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package com.mangopay.android.sdk.model; @RunWith(MockitoJUnitRunner.class) public class MangoCardTest { private static final String CARD_NUMBER = "3569990000000157"; private static final String CARD_EXPIRATION_DATE = "0920"; private static final String CARD_CVX = "123"; private static final String INVALID = ""; @Test public void shouldBeValidatedOk() { MangoCard card = new MangoCard(CARD_NUMBER, CARD_EXPIRATION_DATE, CARD_CVX); card.validate(); assertNotNull(card); assertEquals(CARD_NUMBER, card.getCardNumber()); assertEquals(CARD_EXPIRATION_DATE, card.getExpirationDate()); assertEquals(CARD_CVX, card.getCvx()); }
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // Path: mangopay/src/test/java/com.mangopay.android.sdk/model/MangoCardTest.java import com.mangopay.android.sdk.model.exception.MangoException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package com.mangopay.android.sdk.model; @RunWith(MockitoJUnitRunner.class) public class MangoCardTest { private static final String CARD_NUMBER = "3569990000000157"; private static final String CARD_EXPIRATION_DATE = "0920"; private static final String CARD_CVX = "123"; private static final String INVALID = ""; @Test public void shouldBeValidatedOk() { MangoCard card = new MangoCard(CARD_NUMBER, CARD_EXPIRATION_DATE, CARD_CVX); card.validate(); assertNotNull(card); assertEquals(CARD_NUMBER, card.getCardNumber()); assertEquals(CARD_EXPIRATION_DATE, card.getExpirationDate()); assertEquals(CARD_CVX, card.getCvx()); }
@Test(expected = MangoException.class)
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/domain/BaseInteractorImpl.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/executor/Executor.java // public interface Executor { // // void run(final Interactor interactor); // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/executor/MainThread.java // public interface MainThread { // // void post(final Runnable runnable); // }
import com.mangopay.android.sdk.executor.Executor; import com.mangopay.android.sdk.executor.MainThread;
package com.mangopay.android.sdk.domain; /** * Holds common threading initialization used inside any interactor * * @param <Service> */ public abstract class BaseInteractorImpl<Service> { protected final Executor mExecutor;
// Path: mangopay/src/main/java/com/mangopay/android/sdk/executor/Executor.java // public interface Executor { // // void run(final Interactor interactor); // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/executor/MainThread.java // public interface MainThread { // // void post(final Runnable runnable); // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/domain/BaseInteractorImpl.java import com.mangopay.android.sdk.executor.Executor; import com.mangopay.android.sdk.executor.MainThread; package com.mangopay.android.sdk.domain; /** * Holds common threading initialization used inside any interactor * * @param <Service> */ public abstract class BaseInteractorImpl<Service> { protected final Executor mExecutor;
protected final MainThread mMainThread;
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/model/MangoCard.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // }
import com.mangopay.android.sdk.model.exception.MangoException; import com.mangopay.android.sdk.util.PrintLog;
package com.mangopay.android.sdk.model; /** * This model holds the card information */ public class MangoCard { private static final String CARD_NUMBER_REGEX = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]" + "{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$"; private static final String CARD_EXP_REGEX = "^(0[1-9]|1[0-2])[1-9][0-9]$"; private static final String CARD_CVV_REGEX = "^[0-9]{3,4}$"; private String cardNumber; private String expirationDate; private String cvx; public MangoCard(String cardNumber, String expirationDate, String cvx) { this.cardNumber = cardNumber; this.expirationDate = expirationDate; this.cvx = cvx; } public String getCardNumber() { return cardNumber; } public String getExpirationDate() { return expirationDate; } public String getCvx() { return cvx; }
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/MangoCard.java import com.mangopay.android.sdk.model.exception.MangoException; import com.mangopay.android.sdk.util.PrintLog; package com.mangopay.android.sdk.model; /** * This model holds the card information */ public class MangoCard { private static final String CARD_NUMBER_REGEX = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]" + "{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$"; private static final String CARD_EXP_REGEX = "^(0[1-9]|1[0-2])[1-9][0-9]$"; private static final String CARD_CVV_REGEX = "^[0-9]{3,4}$"; private String cardNumber; private String expirationDate; private String cvx; public MangoCard(String cardNumber, String expirationDate, String cvx) { this.cardNumber = cardNumber; this.expirationDate = expirationDate; this.cvx = cvx; } public String getCardNumber() { return cardNumber; } public String getExpirationDate() { return expirationDate; } public String getCvx() { return cvx; }
public void validate() throws MangoException {
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/model/MangoCard.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // }
import com.mangopay.android.sdk.model.exception.MangoException; import com.mangopay.android.sdk.util.PrintLog;
private String cvx; public MangoCard(String cardNumber, String expirationDate, String cvx) { this.cardNumber = cardNumber; this.expirationDate = expirationDate; this.cvx = cvx; } public String getCardNumber() { return cardNumber; } public String getExpirationDate() { return expirationDate; } public String getCvx() { return cvx; } public void validate() throws MangoException { validateCardExpiration(); validateCardNumber(); validateCardCvx(); } private void validateCardExpiration() { if (!isFieldValid(expirationDate, CARD_EXP_REGEX)) { MangoException error = new MangoException(ErrorCode.EXPIRY_DATE_FORMAT_ERROR.getValue(), "Invalid card expiration date.", ErrorCode.VALIDATION.getValue());
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/MangoCard.java import com.mangopay.android.sdk.model.exception.MangoException; import com.mangopay.android.sdk.util.PrintLog; private String cvx; public MangoCard(String cardNumber, String expirationDate, String cvx) { this.cardNumber = cardNumber; this.expirationDate = expirationDate; this.cvx = cvx; } public String getCardNumber() { return cardNumber; } public String getExpirationDate() { return expirationDate; } public String getCvx() { return cvx; } public void validate() throws MangoException { validateCardExpiration(); validateCardNumber(); validateCardCvx(); } private void validateCardExpiration() { if (!isFieldValid(expirationDate, CARD_EXP_REGEX)) { MangoException error = new MangoException(ErrorCode.EXPIRY_DATE_FORMAT_ERROR.getValue(), "Invalid card expiration date.", ErrorCode.VALIDATION.getValue());
PrintLog.error(error.toString());
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/MangoPayBuilder.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // }
import android.content.Context; import com.mangopay.android.sdk.model.LogLevel; import com.mangopay.android.sdk.util.PrintLog; import java.util.Calendar; import java.util.Date;
} /** * Add the card pre-registration data * * @param preregistrationData needed for the get token request * @return This mango builder. */ public MangoPayBuilder preregistrationData(String preregistrationData) { this.preregistrationData = preregistrationData; return this; } /** * Add the card pre-registration accessKey * * @param accessKey needed for the get token request * @return This mango builder. */ public MangoPayBuilder accessKey(String accessKey) { this.accessKey = accessKey; return this; } /** * Set the SDK Log Level e.g 'NONE' or 'FULL' by default is set to 'NONE' * * @param logLevel needed for logger * @return This mango builder. */
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/MangoPayBuilder.java import android.content.Context; import com.mangopay.android.sdk.model.LogLevel; import com.mangopay.android.sdk.util.PrintLog; import java.util.Calendar; import java.util.Date; } /** * Add the card pre-registration data * * @param preregistrationData needed for the get token request * @return This mango builder. */ public MangoPayBuilder preregistrationData(String preregistrationData) { this.preregistrationData = preregistrationData; return this; } /** * Add the card pre-registration accessKey * * @param accessKey needed for the get token request * @return This mango builder. */ public MangoPayBuilder accessKey(String accessKey) { this.accessKey = accessKey; return this; } /** * Set the SDK Log Level e.g 'NONE' or 'FULL' by default is set to 'NONE' * * @param logLevel needed for logger * @return This mango builder. */
public MangoPayBuilder logLevel(LogLevel logLevel) {
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/MangoPayBuilder.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // }
import android.content.Context; import com.mangopay.android.sdk.model.LogLevel; import com.mangopay.android.sdk.util.PrintLog; import java.util.Calendar; import java.util.Date;
/** * Add the card pre-registration data * * @param preregistrationData needed for the get token request * @return This mango builder. */ public MangoPayBuilder preregistrationData(String preregistrationData) { this.preregistrationData = preregistrationData; return this; } /** * Add the card pre-registration accessKey * * @param accessKey needed for the get token request * @return This mango builder. */ public MangoPayBuilder accessKey(String accessKey) { this.accessKey = accessKey; return this; } /** * Set the SDK Log Level e.g 'NONE' or 'FULL' by default is set to 'NONE' * * @param logLevel needed for logger * @return This mango builder. */ public MangoPayBuilder logLevel(LogLevel logLevel) {
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java // public final class PrintLog { // // private static final String TAG = "MangoPay"; // private static LogLevel LOG_LEVEL = LogLevel.NONE; // // private PrintLog() { // } // // // /** // * Set the level of the logger: 'NONE' or 'FULL'. by default it's 'NONE'. // * // * @param level The level of the logger // */ // public static void setLogLevel(LogLevel level) { // LOG_LEVEL = level; // } // // /** // * Send a DEBUG log message. // * // * @param message The message you would like logged. // */ // public static void debug(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.d(TAG, message.substring(0, 4000)); // debug(message.substring(4000)); // } else { // Log.d(TAG, message); // } // } // // /** // * Send a WARN log message. // * // * @param message The message you would like logged. // */ // public static void warning(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.w(TAG, message.substring(0, 4000)); // warning(message.substring(4000)); // } else { // Log.w(TAG, message); // } // } // // /** // * Send an ERROR log message. // * // * @param message The message you would like logged. // */ // public static void error(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.e(TAG, message.substring(0, 4000)); // error(message.substring(4000)); // } else { // Log.e(TAG, message); // } // } // // /** // * Send an INFO log message. // * // * @param message The message you would like logged. // */ // public static void info(String message) { // if (LOG_LEVEL == LogLevel.NONE) // return; // // if (message.length() > 4000) { // Log.i(TAG, message.substring(0, 4000)); // info(message.substring(4000)); // } else { // Log.i(TAG, message); // } // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/MangoPayBuilder.java import android.content.Context; import com.mangopay.android.sdk.model.LogLevel; import com.mangopay.android.sdk.util.PrintLog; import java.util.Calendar; import java.util.Date; /** * Add the card pre-registration data * * @param preregistrationData needed for the get token request * @return This mango builder. */ public MangoPayBuilder preregistrationData(String preregistrationData) { this.preregistrationData = preregistrationData; return this; } /** * Add the card pre-registration accessKey * * @param accessKey needed for the get token request * @return This mango builder. */ public MangoPayBuilder accessKey(String accessKey) { this.accessKey = accessKey; return this; } /** * Set the SDK Log Level e.g 'NONE' or 'FULL' by default is set to 'NONE' * * @param logLevel needed for logger * @return This mango builder. */ public MangoPayBuilder logLevel(LogLevel logLevel) {
PrintLog.setLogLevel(logLevel);
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/domain/service/ServiceCallback.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // }
import com.mangopay.android.sdk.model.exception.MangoException;
package com.mangopay.android.sdk.domain.service; public interface ServiceCallback<T> { void success(T jsonResponse);
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/domain/service/ServiceCallback.java import com.mangopay.android.sdk.model.exception.MangoException; package com.mangopay.android.sdk.domain.service; public interface ServiceCallback<T> { void success(T jsonResponse);
void failure(MangoException error);
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // }
import android.util.Log; import com.mangopay.android.sdk.model.LogLevel;
package com.mangopay.android.sdk.util; public final class PrintLog { private static final String TAG = "MangoPay";
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/LogLevel.java // public enum LogLevel { // NONE, FULL // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/util/PrintLog.java import android.util.Log; import com.mangopay.android.sdk.model.LogLevel; package com.mangopay.android.sdk.util; public final class PrintLog { private static final String TAG = "MangoPay";
private static LogLevel LOG_LEVEL = LogLevel.NONE;
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/ErrorCode.java // public enum ErrorCode { // // VALIDATION("sdk-validation"), // SERVER_ERROR("server-error"), // SDK_ERROR("sdk-error"), // // MISSING_FIELD_ERROR("105201"), // CARD_NUMBER_FORMAT_ERROR("105202"), // EXPIRY_DATE_FORMAT_ERROR("105203"), // CVV_FORMAT_ERROR("105204"); // // private String id; // // ErrorCode(String id) { // this.id = id; // } // // public String getValue() { // return this.id; // } // }
import com.mangopay.android.sdk.model.ErrorCode;
package com.mangopay.android.sdk.model.exception; /** * Possible error returned from the mangoPay servers */ public class MangoException extends RuntimeException { private String id; private String type; private long timestamp; public MangoException(Throwable throwable) { super(throwable);
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/ErrorCode.java // public enum ErrorCode { // // VALIDATION("sdk-validation"), // SERVER_ERROR("server-error"), // SDK_ERROR("sdk-error"), // // MISSING_FIELD_ERROR("105201"), // CARD_NUMBER_FORMAT_ERROR("105202"), // EXPIRY_DATE_FORMAT_ERROR("105203"), // CVV_FORMAT_ERROR("105204"); // // private String id; // // ErrorCode(String id) { // this.id = id; // } // // public String getValue() { // return this.id; // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java import com.mangopay.android.sdk.model.ErrorCode; package com.mangopay.android.sdk.model.exception; /** * Possible error returned from the mangoPay servers */ public class MangoException extends RuntimeException { private String id; private String type; private long timestamp; public MangoException(Throwable throwable) { super(throwable);
this.id = ErrorCode.SDK_ERROR.getValue();
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/model/RequestObject.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/domain/service/ServiceCallback.java // public interface ServiceCallback<T> { // // void success(T jsonResponse); // // void failure(MangoException error); // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // }
import com.mangopay.android.sdk.domain.service.ServiceCallback; import com.mangopay.android.sdk.model.exception.MangoException; import java.lang.reflect.Field; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List;
package com.mangopay.android.sdk.model; public class RequestObject { /** * Using reflection we are returning a List of SimpleEntry objects generated * from our fields, used on our API requests */ public List<AbstractMap.SimpleEntry<String, String>> getFields(ServiceCallback callback) { Field[] declaredFields = this.getClass().getDeclaredFields(); List<AbstractMap.SimpleEntry<String, String>> params = new ArrayList<>(declaredFields.length); for (Field field : declaredFields) { try { field.setAccessible(true); String value = (String) field.get(this); params.add(new AbstractMap.SimpleEntry<>(field.getName(), value)); } catch (IllegalAccessException e) { if (callback != null)
// Path: mangopay/src/main/java/com/mangopay/android/sdk/domain/service/ServiceCallback.java // public interface ServiceCallback<T> { // // void success(T jsonResponse); // // void failure(MangoException error); // } // // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // Path: mangopay/src/main/java/com/mangopay/android/sdk/model/RequestObject.java import com.mangopay.android.sdk.domain.service.ServiceCallback; import com.mangopay.android.sdk.model.exception.MangoException; import java.lang.reflect.Field; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; package com.mangopay.android.sdk.model; public class RequestObject { /** * Using reflection we are returning a List of SimpleEntry objects generated * from our fields, used on our API requests */ public List<AbstractMap.SimpleEntry<String, String>> getFields(ServiceCallback callback) { Field[] declaredFields = this.getClass().getDeclaredFields(); List<AbstractMap.SimpleEntry<String, String>> params = new ArrayList<>(declaredFields.length); for (Field field : declaredFields) { try { field.setAccessible(true); String value = (String) field.get(this); params.add(new AbstractMap.SimpleEntry<>(field.getName(), value)); } catch (IllegalAccessException e) { if (callback != null)
callback.failure(new MangoException(e));
Mangopay/cardregistration-android-kit
mangopay/src/test/java/com.mangopay.android.sdk/model/MangoSettingsTest.java
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // }
import com.mangopay.android.sdk.model.exception.MangoException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package com.mangopay.android.sdk.model; @RunWith(MockitoJUnitRunner.class) public class MangoSettingsTest { private static final String BASE_URL = "https://www.mangopay.com/"; private static final String CLIENT_ID = "123"; private static final String CARD_PRE_REG_ID = "preId123"; private static final String CARD_REG_URL = "cardRegUrl"; private static final String PRE_REG_DATA = "preRegData"; private static final String ACCESS_KEY = "accessKey"; private static final String INVALID = ""; @Test public void shouldBeValidatedOk() { MangoSettings settings = new MangoSettings(BASE_URL, CLIENT_ID, CARD_PRE_REG_ID, CARD_REG_URL, PRE_REG_DATA, ACCESS_KEY); settings.validate(); assertNotNull(settings); assertEquals(BASE_URL, settings.getBaseURL()); assertEquals(CLIENT_ID, settings.getClientId()); assertEquals(CARD_PRE_REG_ID, settings.getCardPreregistrationId()); assertEquals(CARD_REG_URL, settings.getCardRegistrationURL()); assertEquals(PRE_REG_DATA, settings.getPreregistrationData()); assertEquals(ACCESS_KEY, settings.getAccessKey()); }
// Path: mangopay/src/main/java/com/mangopay/android/sdk/model/exception/MangoException.java // public class MangoException extends RuntimeException { // // private String id; // private String type; // private long timestamp; // // public MangoException(Throwable throwable) { // super(throwable); // this.id = ErrorCode.SDK_ERROR.getValue(); // this.timestamp = System.currentTimeMillis(); // } // // public MangoException(String id, String message) { // this(id, message, null); // } // // public MangoException(String id, String message, String type) { // super(message); // this.id = id; // this.type = type; // this.timestamp = System.currentTimeMillis(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // MangoException error = (MangoException) o; // // return !(id != null ? !id.equals(error.id) : error.id != null); // // } // // @Override public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override public String toString() { // return "MangoError{" + // "id='" + id + '\'' + // ", message='" + getMessage() + '\'' + // ", type='" + type + '\'' + // ", timestamp=" + timestamp + // '}'; // } // } // Path: mangopay/src/test/java/com.mangopay.android.sdk/model/MangoSettingsTest.java import com.mangopay.android.sdk.model.exception.MangoException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package com.mangopay.android.sdk.model; @RunWith(MockitoJUnitRunner.class) public class MangoSettingsTest { private static final String BASE_URL = "https://www.mangopay.com/"; private static final String CLIENT_ID = "123"; private static final String CARD_PRE_REG_ID = "preId123"; private static final String CARD_REG_URL = "cardRegUrl"; private static final String PRE_REG_DATA = "preRegData"; private static final String ACCESS_KEY = "accessKey"; private static final String INVALID = ""; @Test public void shouldBeValidatedOk() { MangoSettings settings = new MangoSettings(BASE_URL, CLIENT_ID, CARD_PRE_REG_ID, CARD_REG_URL, PRE_REG_DATA, ACCESS_KEY); settings.validate(); assertNotNull(settings); assertEquals(BASE_URL, settings.getBaseURL()); assertEquals(CLIENT_ID, settings.getClientId()); assertEquals(CARD_PRE_REG_ID, settings.getCardPreregistrationId()); assertEquals(CARD_REG_URL, settings.getCardRegistrationURL()); assertEquals(PRE_REG_DATA, settings.getPreregistrationData()); assertEquals(ACCESS_KEY, settings.getAccessKey()); }
@Test(expected = MangoException.class)
bbottema/outlook-message-parser
src/main/java/org/simplejavamail/jakarta/mail/internet/InternetAddress.java
// Path: src/main/java/org/simplejavamail/com/sun/mail/util/PropUtil.java // public class PropUtil { // // // No one should instantiate this class. // private PropUtil() { // } // // /** // * Get an integer valued property. // * // * @param props the properties // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static int getIntProperty(Properties props, String name, int def) { // return getInt(getProp(props, name), def); // } // // /** // * Get a boolean valued property. // * // * @param props the properties // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static boolean getBooleanProperty(Properties props, // String name, boolean def) { // return getBoolean(getProp(props, name), def); // } // // /** // * Get a boolean valued System property. // * // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static boolean getBooleanSystemProperty(String name, boolean def) { // try { // return getBoolean(getProp(System.getProperties(), name), def); // } catch (SecurityException sex) { // // fall through... // } // // /* // * If we can't get the entire System Properties object because // * of a SecurityException, just ask for the specific property. // */ // try { // String value = System.getProperty(name); // if (value == null) // return def; // if (def) // return !value.equalsIgnoreCase("false"); // else // return value.equalsIgnoreCase("true"); // } catch (SecurityException sex) { // return def; // } // } // // /** // * Get the value of the specified property. // * If the "get" method returns null, use the getProperty method, // * which might cascade to a default Properties object. // */ // private static Object getProp(Properties props, String name) { // Object val = props.get(name); // if (val != null) // return val; // else // return props.getProperty(name); // } // // /** // * Interpret the value object as an integer, // * returning def if unable. // */ // private static int getInt(Object value, int def) { // if (value == null) // return def; // if (value instanceof String) { // try { // String s = (String)value; // if (s.startsWith("0x")) // return Integer.parseInt(s.substring(2), 16); // else // return Integer.parseInt(s); // } catch (NumberFormatException nfex) { } // } // if (value instanceof Integer) // return ((Integer)value).intValue(); // return def; // } // // /** // * Interpret the value object as a boolean, // * returning def if unable. // */ // private static boolean getBoolean(Object value, boolean def) { // if (value == null) // return def; // if (value instanceof String) { // /* // * If the default is true, only "false" turns it off. // * If the default is false, only "true" turns it on. // */ // if (def) // return !((String)value).equalsIgnoreCase("false"); // else // return ((String)value).equalsIgnoreCase("true"); // } // if (value instanceof Boolean) // return ((Boolean)value).booleanValue(); // return def; // } // }
import org.simplejavamail.com.sun.mail.util.PropUtil; import org.simplejavamail.jakarta.mail.*; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Locale; import java.nio.charset.StandardCharsets;
/* * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.simplejavamail.jakarta.mail.internet; /** * This class represents an Internet email address using the syntax * of <a href="http://www.ietf.org/rfc/rfc822.txt" target="_top">RFC822</a>. * Typical address syntax is of the form "[email protected]" or * "Personal Name &lt;[email protected]&gt;". * * @author Bill Shannon * @author John Mani */ public class InternetAddress extends Address implements Cloneable { protected String address; // email address /** * The personal name. */ protected String personal; /** * The RFC 2047 encoded version of the personal name. <p> * * This field and the <code>personal</code> field track each * other, so if a subclass sets one of these fields directly, it * should set the other to <code>null</code>, so that it is * suitably recomputed. */ protected String encodedPersonal; private static final long serialVersionUID = -7507595530758302903L; private static final boolean ignoreBogusGroupName =
// Path: src/main/java/org/simplejavamail/com/sun/mail/util/PropUtil.java // public class PropUtil { // // // No one should instantiate this class. // private PropUtil() { // } // // /** // * Get an integer valued property. // * // * @param props the properties // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static int getIntProperty(Properties props, String name, int def) { // return getInt(getProp(props, name), def); // } // // /** // * Get a boolean valued property. // * // * @param props the properties // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static boolean getBooleanProperty(Properties props, // String name, boolean def) { // return getBoolean(getProp(props, name), def); // } // // /** // * Get a boolean valued System property. // * // * @param name the property name // * @param def default value if property not found // * @return the property value // */ // public static boolean getBooleanSystemProperty(String name, boolean def) { // try { // return getBoolean(getProp(System.getProperties(), name), def); // } catch (SecurityException sex) { // // fall through... // } // // /* // * If we can't get the entire System Properties object because // * of a SecurityException, just ask for the specific property. // */ // try { // String value = System.getProperty(name); // if (value == null) // return def; // if (def) // return !value.equalsIgnoreCase("false"); // else // return value.equalsIgnoreCase("true"); // } catch (SecurityException sex) { // return def; // } // } // // /** // * Get the value of the specified property. // * If the "get" method returns null, use the getProperty method, // * which might cascade to a default Properties object. // */ // private static Object getProp(Properties props, String name) { // Object val = props.get(name); // if (val != null) // return val; // else // return props.getProperty(name); // } // // /** // * Interpret the value object as an integer, // * returning def if unable. // */ // private static int getInt(Object value, int def) { // if (value == null) // return def; // if (value instanceof String) { // try { // String s = (String)value; // if (s.startsWith("0x")) // return Integer.parseInt(s.substring(2), 16); // else // return Integer.parseInt(s); // } catch (NumberFormatException nfex) { } // } // if (value instanceof Integer) // return ((Integer)value).intValue(); // return def; // } // // /** // * Interpret the value object as a boolean, // * returning def if unable. // */ // private static boolean getBoolean(Object value, boolean def) { // if (value == null) // return def; // if (value instanceof String) { // /* // * If the default is true, only "false" turns it off. // * If the default is false, only "true" turns it on. // */ // if (def) // return !((String)value).equalsIgnoreCase("false"); // else // return ((String)value).equalsIgnoreCase("true"); // } // if (value instanceof Boolean) // return ((Boolean)value).booleanValue(); // return def; // } // } // Path: src/main/java/org/simplejavamail/jakarta/mail/internet/InternetAddress.java import org.simplejavamail.com.sun.mail.util.PropUtil; import org.simplejavamail.jakarta.mail.*; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Locale; import java.nio.charset.StandardCharsets; /* * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.simplejavamail.jakarta.mail.internet; /** * This class represents an Internet email address using the syntax * of <a href="http://www.ietf.org/rfc/rfc822.txt" target="_top">RFC822</a>. * Typical address syntax is of the form "[email protected]" or * "Personal Name &lt;[email protected]&gt;". * * @author Bill Shannon * @author John Mani */ public class InternetAddress extends Address implements Cloneable { protected String address; // email address /** * The personal name. */ protected String personal; /** * The RFC 2047 encoded version of the personal name. <p> * * This field and the <code>personal</code> field track each * other, so if a subclass sets one of these fields directly, it * should set the other to <code>null</code>, so that it is * suitably recomputed. */ protected String encodedPersonal; private static final long serialVersionUID = -7507595530758302903L; private static final boolean ignoreBogusGroupName =
PropUtil.getBooleanSystemProperty(
bbottema/outlook-message-parser
src/test/java/org/simplejavamail/outlookmessageparser/model/OutlookMessageTest.java
// Path: src/main/java/org/simplejavamail/outlookmessageparser/model/OutlookSmime.java // public static class OutlookSmimeApplicationSmime extends OutlookSmime { // private final String smimeMime; // private final String smimeType; // private final String smimeName; // // public OutlookSmimeApplicationSmime(String smimeMime, String smimeType, String smimeName) { // this.smimeMime = smimeMime; // this.smimeType = smimeType; // this.smimeName = smimeName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // OutlookSmimeApplicationSmime that = (OutlookSmimeApplicationSmime) o; // return Objects.equals(smimeMime, that.smimeMime) && // Objects.equals(smimeType, that.smimeType) && // Objects.equals(smimeName, that.smimeName); // } // // @Override // public int hashCode() { // return Objects.hash(smimeMime, smimeType, smimeName); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("OutlookSmimeApplicationSmime{"); // sb.append("smimeMime='").append(smimeMime).append('\''); // sb.append(", smimeType='").append(smimeType).append('\''); // sb.append(", smimeName='").append(smimeName).append('\''); // sb.append('}'); // return sb.toString(); // } // // public String getSmimeMime() { return smimeMime; } // public String getSmimeType() { return smimeType; } // public String getSmimeName() { return smimeName; } // }
import org.junit.Test; import org.simplejavamail.outlookmessageparser.model.OutlookSmime.OutlookSmimeApplicationSmime; import static org.assertj.core.api.Assertions.assertThat;
package org.simplejavamail.outlookmessageparser.model; public class OutlookMessageTest { @Test public void testSetSmimeNull() { OutlookMessage msg = new OutlookMessage(); msg.setSmimeApplicationSmime(null); assertThat(msg.getSmime()).isNull(); msg.setSmimeApplicationSmime(""); assertThat(msg.getSmime()).isNull(); msg.setSmimeApplicationSmime("moomoo"); assertThat(msg.getSmime()).isNull(); } @Test public void testSetSmimeNonNull() { // application/pkcs7-mime;smime-type=signed-data;name=smime.p7m testSmime("application/pkcs7-mime", "application/pkcs7-mime", null, null); testSmime("application/pkcs7-mime;", "application/pkcs7-mime", null, null); testSmime("application/pkcs7-mime;name=moo", "application/pkcs7-mime", null, "moo"); testSmime("application/pkcs7-mime;smime-type=signed-data;name=smime.p7m", "application/pkcs7-mime", "signed-data", "smime.p7m"); testSmime("application/pkcs7-mime;name=smime.p7m;smime-type=signed-data", "application/pkcs7-mime", "signed-data", "smime.p7m"); testSmime("application/pkcs7-mime;name=smime.p7m;smime-type=signed-data;", "application/pkcs7-mime", "signed-data", "smime.p7m"); } private void testSmime(String smimeHeader, String smimeMime, String smimeType, String smimeName) { OutlookMessage msg = new OutlookMessage(); msg.setSmimeApplicationSmime(smimeHeader);
// Path: src/main/java/org/simplejavamail/outlookmessageparser/model/OutlookSmime.java // public static class OutlookSmimeApplicationSmime extends OutlookSmime { // private final String smimeMime; // private final String smimeType; // private final String smimeName; // // public OutlookSmimeApplicationSmime(String smimeMime, String smimeType, String smimeName) { // this.smimeMime = smimeMime; // this.smimeType = smimeType; // this.smimeName = smimeName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // OutlookSmimeApplicationSmime that = (OutlookSmimeApplicationSmime) o; // return Objects.equals(smimeMime, that.smimeMime) && // Objects.equals(smimeType, that.smimeType) && // Objects.equals(smimeName, that.smimeName); // } // // @Override // public int hashCode() { // return Objects.hash(smimeMime, smimeType, smimeName); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("OutlookSmimeApplicationSmime{"); // sb.append("smimeMime='").append(smimeMime).append('\''); // sb.append(", smimeType='").append(smimeType).append('\''); // sb.append(", smimeName='").append(smimeName).append('\''); // sb.append('}'); // return sb.toString(); // } // // public String getSmimeMime() { return smimeMime; } // public String getSmimeType() { return smimeType; } // public String getSmimeName() { return smimeName; } // } // Path: src/test/java/org/simplejavamail/outlookmessageparser/model/OutlookMessageTest.java import org.junit.Test; import org.simplejavamail.outlookmessageparser.model.OutlookSmime.OutlookSmimeApplicationSmime; import static org.assertj.core.api.Assertions.assertThat; package org.simplejavamail.outlookmessageparser.model; public class OutlookMessageTest { @Test public void testSetSmimeNull() { OutlookMessage msg = new OutlookMessage(); msg.setSmimeApplicationSmime(null); assertThat(msg.getSmime()).isNull(); msg.setSmimeApplicationSmime(""); assertThat(msg.getSmime()).isNull(); msg.setSmimeApplicationSmime("moomoo"); assertThat(msg.getSmime()).isNull(); } @Test public void testSetSmimeNonNull() { // application/pkcs7-mime;smime-type=signed-data;name=smime.p7m testSmime("application/pkcs7-mime", "application/pkcs7-mime", null, null); testSmime("application/pkcs7-mime;", "application/pkcs7-mime", null, null); testSmime("application/pkcs7-mime;name=moo", "application/pkcs7-mime", null, "moo"); testSmime("application/pkcs7-mime;smime-type=signed-data;name=smime.p7m", "application/pkcs7-mime", "signed-data", "smime.p7m"); testSmime("application/pkcs7-mime;name=smime.p7m;smime-type=signed-data", "application/pkcs7-mime", "signed-data", "smime.p7m"); testSmime("application/pkcs7-mime;name=smime.p7m;smime-type=signed-data;", "application/pkcs7-mime", "signed-data", "smime.p7m"); } private void testSmime(String smimeHeader, String smimeMime, String smimeType, String smimeName) { OutlookMessage msg = new OutlookMessage(); msg.setSmimeApplicationSmime(smimeHeader);
OutlookSmimeApplicationSmime smime = (OutlookSmimeApplicationSmime) msg.getSmime();
saltlab/clematis
src/main/java/com/clematis/core/episode/Episode.java
// Path: src/main/java/com/clematis/core/trace/TraceObject.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public class TraceObject implements Comparable<TraceObject> { // private int id; // private int counter; // private String messageType; // private long timeStamp; // private boolean isEpisodeSource; // // private boolean isBookmarked; // // public TraceObject() { // isEpisodeSource = false; // // isBookmarked = false; // } // // public int getCounter() { // return counter; // } // public void setCounter(int counter) { // this.counter = counter; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMessageType() { // return messageType; // } // public void setMessageType(String messageType) { // this.messageType = messageType; // } // public long getTimeStamp() { // return timeStamp; // } // public void setTimeStamp(long timeStamp) { // this.timeStamp = timeStamp; // } // public int compareTo(TraceObject o) { // if (counter < o.getCounter()) // return -1; // else if (counter > o.getCounter()) // return 1; // return 0; // } // // public boolean isEpisodeSource() { // return isEpisodeSource; // } // // public void setEpisodeSource(boolean isEpisodeSource) { // this.isEpisodeSource = isEpisodeSource; // } // /* // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // */ // }
import javax.xml.bind.annotation.XmlRootElement; import com.clematis.core.trace.TraceObject;
package com.clematis.core.episode; @XmlRootElement public class Episode { // private EpisodeSource source;
// Path: src/main/java/com/clematis/core/trace/TraceObject.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public class TraceObject implements Comparable<TraceObject> { // private int id; // private int counter; // private String messageType; // private long timeStamp; // private boolean isEpisodeSource; // // private boolean isBookmarked; // // public TraceObject() { // isEpisodeSource = false; // // isBookmarked = false; // } // // public int getCounter() { // return counter; // } // public void setCounter(int counter) { // this.counter = counter; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMessageType() { // return messageType; // } // public void setMessageType(String messageType) { // this.messageType = messageType; // } // public long getTimeStamp() { // return timeStamp; // } // public void setTimeStamp(long timeStamp) { // this.timeStamp = timeStamp; // } // public int compareTo(TraceObject o) { // if (counter < o.getCounter()) // return -1; // else if (counter > o.getCounter()) // return 1; // return 0; // } // // public boolean isEpisodeSource() { // return isEpisodeSource; // } // // public void setEpisodeSource(boolean isEpisodeSource) { // this.isEpisodeSource = isEpisodeSource; // } // /* // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // */ // } // Path: src/main/java/com/clematis/core/episode/Episode.java import javax.xml.bind.annotation.XmlRootElement; import com.clematis.core.trace.TraceObject; package com.clematis.core.episode; @XmlRootElement public class Episode { // private EpisodeSource source;
private TraceObject source;
saltlab/clematis
src/main/java/com/clematis/visual/EpisodeGraph.java
// Path: src/main/java/com/clematis/core/episode/Episode.java // @XmlRootElement // public class Episode { // // private EpisodeSource source; // private TraceObject source; // private EpisodeTrace trace; // private String dom; // private boolean isBookmarked; // // public Episode() { // // } // // /* // * public Episode(EpisodeSource source) { trace = new EpisodeTrace(); } // */ // public Episode(TraceObject source) { // trace = new EpisodeTrace(); // this.source = source; // } // // public void addToTrace(TraceObject to) { // trace.addToTrace(to); // } // // /* // * public EpisodeSource getSource() { return source; } public void setSource(EpisodeSource // * source) { this.source = source; } // */public EpisodeTrace getTrace() { // return trace; // } // // public void setTrace(EpisodeTrace trace) { // this.trace = trace; // } // // public String getDom() { // return dom; // } // // public void setDom(String dom) { // this.dom = dom; // } // // public TraceObject getSource() { // return source; // } // // public void setSource(TraceObject source) { // this.source = source; // } // // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // } // // Path: src/main/java/com/clematis/core/trace/TraceObject.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public class TraceObject implements Comparable<TraceObject> { // private int id; // private int counter; // private String messageType; // private long timeStamp; // private boolean isEpisodeSource; // // private boolean isBookmarked; // // public TraceObject() { // isEpisodeSource = false; // // isBookmarked = false; // } // // public int getCounter() { // return counter; // } // public void setCounter(int counter) { // this.counter = counter; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMessageType() { // return messageType; // } // public void setMessageType(String messageType) { // this.messageType = messageType; // } // public long getTimeStamp() { // return timeStamp; // } // public void setTimeStamp(long timeStamp) { // this.timeStamp = timeStamp; // } // public int compareTo(TraceObject o) { // if (counter < o.getCounter()) // return -1; // else if (counter > o.getCounter()) // return 1; // return 0; // } // // public boolean isEpisodeSource() { // return isEpisodeSource; // } // // public void setEpisodeSource(boolean isEpisodeSource) { // this.isEpisodeSource = isEpisodeSource; // } // /* // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // */ // }
import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Date; import org.jgrapht.ext.DOTExporter; import org.jgrapht.ext.StringEdgeNameProvider; import org.jgrapht.ext.StringNameProvider; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedMultigraph; import com.crawljax.util.Helper; import com.clematis.core.episode.Episode; import com.clematis.core.trace.TraceObject;
System.setOut(output); System.out.println("var causalLinks = new Array();"); System.setOut(oldOut); } catch (IOException e1) { e1.printStackTrace(); } } @SuppressWarnings("unchecked") public void createGraph() { Date d = new Date(); FileWriter fos; for (Episode e: el){ // Populate graph with an edge for each episode addVertex(e); } for (int i = 0; i< el.size(); i++) { // Add causal edges between episodes Episode currentEpisode = el.get(i); // If the source is not included in the trace, add it if(!currentEpisode.getTrace().getTrace().contains(currentEpisode.getSource())) { // Need entire episode (including source) when looking for causality currentEpisode.getTrace().addToTrace(currentEpisode.getSource()); }
// Path: src/main/java/com/clematis/core/episode/Episode.java // @XmlRootElement // public class Episode { // // private EpisodeSource source; // private TraceObject source; // private EpisodeTrace trace; // private String dom; // private boolean isBookmarked; // // public Episode() { // // } // // /* // * public Episode(EpisodeSource source) { trace = new EpisodeTrace(); } // */ // public Episode(TraceObject source) { // trace = new EpisodeTrace(); // this.source = source; // } // // public void addToTrace(TraceObject to) { // trace.addToTrace(to); // } // // /* // * public EpisodeSource getSource() { return source; } public void setSource(EpisodeSource // * source) { this.source = source; } // */public EpisodeTrace getTrace() { // return trace; // } // // public void setTrace(EpisodeTrace trace) { // this.trace = trace; // } // // public String getDom() { // return dom; // } // // public void setDom(String dom) { // this.dom = dom; // } // // public TraceObject getSource() { // return source; // } // // public void setSource(TraceObject source) { // this.source = source; // } // // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // } // // Path: src/main/java/com/clematis/core/trace/TraceObject.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public class TraceObject implements Comparable<TraceObject> { // private int id; // private int counter; // private String messageType; // private long timeStamp; // private boolean isEpisodeSource; // // private boolean isBookmarked; // // public TraceObject() { // isEpisodeSource = false; // // isBookmarked = false; // } // // public int getCounter() { // return counter; // } // public void setCounter(int counter) { // this.counter = counter; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getMessageType() { // return messageType; // } // public void setMessageType(String messageType) { // this.messageType = messageType; // } // public long getTimeStamp() { // return timeStamp; // } // public void setTimeStamp(long timeStamp) { // this.timeStamp = timeStamp; // } // public int compareTo(TraceObject o) { // if (counter < o.getCounter()) // return -1; // else if (counter > o.getCounter()) // return 1; // return 0; // } // // public boolean isEpisodeSource() { // return isEpisodeSource; // } // // public void setEpisodeSource(boolean isEpisodeSource) { // this.isEpisodeSource = isEpisodeSource; // } // /* // public boolean getIsBookmarked() { // return isBookmarked; // } // // public void setIsBookmarked(boolean isBookmarked) { // this.isBookmarked = isBookmarked; // } // */ // } // Path: src/main/java/com/clematis/visual/EpisodeGraph.java import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Date; import org.jgrapht.ext.DOTExporter; import org.jgrapht.ext.StringEdgeNameProvider; import org.jgrapht.ext.StringNameProvider; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedMultigraph; import com.crawljax.util.Helper; import com.clematis.core.episode.Episode; import com.clematis.core.trace.TraceObject; System.setOut(output); System.out.println("var causalLinks = new Array();"); System.setOut(oldOut); } catch (IOException e1) { e1.printStackTrace(); } } @SuppressWarnings("unchecked") public void createGraph() { Date d = new Date(); FileWriter fos; for (Episode e: el){ // Populate graph with an edge for each episode addVertex(e); } for (int i = 0; i< el.size(); i++) { // Add causal edges between episodes Episode currentEpisode = el.get(i); // If the source is not included in the trace, add it if(!currentEpisode.getTrace().getTrace().contains(currentEpisode.getSource())) { // Need entire episode (including source) when looking for causality currentEpisode.getTrace().addToTrace(currentEpisode.getSource()); }
for (TraceObject to : currentEpisode.getTrace().getTrace()) {
Fedict/eid-viewer
eid-viewer-lib/src/main/java/be/fedict/eidviewer/lib/file/imports/Version35EidFile.java
// Path: eid-viewer-lib/src/main/java/be/fedict/eidviewer/lib/X509CertificateChainAndTrust.java // public class X509CertificateChainAndTrust // { // private List<X509Certificate> certificates; // private List<X509CertificateAndTrust> certificatesAndTrusts; // private String trustDomain; // private Exception validationException; // private RevocationValuesType revocationValues; // private List<String> invalidReasons; // private boolean validating, validated,trusted; // // public X509CertificateChainAndTrust(String trustDomain, List<X509Certificate> certificates) // { // this.trustDomain=trustDomain; // this.certificates=certificates; // this.certificatesAndTrusts=new ArrayList<X509CertificateAndTrust>(); // for(X509Certificate certificate : certificates) // this.certificatesAndTrusts.add(new X509CertificateAndTrust(certificate, trustDomain)); // this.validated = false; // this.trusted = false; // } // // public List<X509Certificate> getCertificates() // { // return certificates; // } // // public List<X509CertificateAndTrust> getCertificatesAndTrusts() // { // return certificatesAndTrusts; // } // // public Exception getValidationException() // { // return validationException; // } // // public List<String> getInvalidReasons() // { // return invalidReasons; // } // // public RevocationValuesType getRevocationValues() // { // return revocationValues; // } // // public boolean isValidating() // { // return validating; // } // // public boolean isTrusted() // { // return trusted; // } // // public boolean isValidated() // { // return validated; // } // // public String getTrustDomain() // { // return trustDomain; // } // // /* ------------------------------------------------------------------------------ */ // // public void setValidationException(Exception validationException) // { // this.validationException = validationException; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setTrustServiceException(Exception trustServiceException) // { // this.validationException = trustServiceException; // this.validating=false; // this.validated=false; // this.trusted=false; // propagate(); // } // // public void setInvalidReasons(List<String> invalidReasons) // { // this.invalidReasons = invalidReasons; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setRevocationValues(RevocationValuesType revocationValues) // { // this.revocationValues=revocationValues; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setValidating() // { // this.validating=true; // propagate(); // } // // public void setTrusted() // { // this.validating=false; // this.validated=true; // this.trusted=true; // propagate(); // } // // private void propagate() // { // for(X509CertificateAndTrust certificate : certificatesAndTrusts) // { // certificate.setValidating(this.isValidating()); // certificate.setValidated(this.isValidated()); // certificate.setValidationException(this.getValidationException()); // certificate.setInvalidReasons(this.getInvalidReasons()); // certificate.setTrusted(this.isTrusted()); // } // } // // @Override // public String toString() // { // return TextFormatHelper.join(certificatesAndTrusts," signed by "); // } // }
import be.fedict.eidviewer.lib.file.helper.TLVEntry; import be.fedict.eid.applet.service.Address; import be.fedict.eid.applet.service.Identity; import be.fedict.eid.applet.service.impl.tlv.TlvParser; import be.fedict.eidviewer.lib.EidData; import be.fedict.eidviewer.lib.X509CertificateChainAndTrust; import be.fedict.eidviewer.lib.file.helper.TextFormatHelper; import be.fedict.trust.client.TrustServiceDomains; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger;
certEntry2.data)); break; case 4: rootCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream( certEntry2.data)); break; } } break; } } } break; } } } break; } } if (rootCert != null) { if (rrnCert != null) { List<X509Certificate> signChain = new LinkedList<X509Certificate>(); signChain.add(rrnCert); signChain.add(rootCert);
// Path: eid-viewer-lib/src/main/java/be/fedict/eidviewer/lib/X509CertificateChainAndTrust.java // public class X509CertificateChainAndTrust // { // private List<X509Certificate> certificates; // private List<X509CertificateAndTrust> certificatesAndTrusts; // private String trustDomain; // private Exception validationException; // private RevocationValuesType revocationValues; // private List<String> invalidReasons; // private boolean validating, validated,trusted; // // public X509CertificateChainAndTrust(String trustDomain, List<X509Certificate> certificates) // { // this.trustDomain=trustDomain; // this.certificates=certificates; // this.certificatesAndTrusts=new ArrayList<X509CertificateAndTrust>(); // for(X509Certificate certificate : certificates) // this.certificatesAndTrusts.add(new X509CertificateAndTrust(certificate, trustDomain)); // this.validated = false; // this.trusted = false; // } // // public List<X509Certificate> getCertificates() // { // return certificates; // } // // public List<X509CertificateAndTrust> getCertificatesAndTrusts() // { // return certificatesAndTrusts; // } // // public Exception getValidationException() // { // return validationException; // } // // public List<String> getInvalidReasons() // { // return invalidReasons; // } // // public RevocationValuesType getRevocationValues() // { // return revocationValues; // } // // public boolean isValidating() // { // return validating; // } // // public boolean isTrusted() // { // return trusted; // } // // public boolean isValidated() // { // return validated; // } // // public String getTrustDomain() // { // return trustDomain; // } // // /* ------------------------------------------------------------------------------ */ // // public void setValidationException(Exception validationException) // { // this.validationException = validationException; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setTrustServiceException(Exception trustServiceException) // { // this.validationException = trustServiceException; // this.validating=false; // this.validated=false; // this.trusted=false; // propagate(); // } // // public void setInvalidReasons(List<String> invalidReasons) // { // this.invalidReasons = invalidReasons; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setRevocationValues(RevocationValuesType revocationValues) // { // this.revocationValues=revocationValues; // this.validating=false; // this.validated=true; // this.trusted=false; // propagate(); // } // // public void setValidating() // { // this.validating=true; // propagate(); // } // // public void setTrusted() // { // this.validating=false; // this.validated=true; // this.trusted=true; // propagate(); // } // // private void propagate() // { // for(X509CertificateAndTrust certificate : certificatesAndTrusts) // { // certificate.setValidating(this.isValidating()); // certificate.setValidated(this.isValidated()); // certificate.setValidationException(this.getValidationException()); // certificate.setInvalidReasons(this.getInvalidReasons()); // certificate.setTrusted(this.isTrusted()); // } // } // // @Override // public String toString() // { // return TextFormatHelper.join(certificatesAndTrusts," signed by "); // } // } // Path: eid-viewer-lib/src/main/java/be/fedict/eidviewer/lib/file/imports/Version35EidFile.java import be.fedict.eidviewer.lib.file.helper.TLVEntry; import be.fedict.eid.applet.service.Address; import be.fedict.eid.applet.service.Identity; import be.fedict.eid.applet.service.impl.tlv.TlvParser; import be.fedict.eidviewer.lib.EidData; import be.fedict.eidviewer.lib.X509CertificateChainAndTrust; import be.fedict.eidviewer.lib.file.helper.TextFormatHelper; import be.fedict.trust.client.TrustServiceDomains; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; certEntry2.data)); break; case 4: rootCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream( certEntry2.data)); break; } } break; } } } break; } } } break; } } if (rootCert != null) { if (rrnCert != null) { List<X509Certificate> signChain = new LinkedList<X509Certificate>(); signChain.add(rrnCert); signChain.add(rootCert);
eidData.setRRNCertChain(new X509CertificateChainAndTrust(
Fedict/eid-viewer
eid-viewer-gui/src/main/java/be/fedict/eidviewer/gui/ViewerPrefs.java
// Path: eid-viewer-gui/src/main/java/be/fedict/eidviewer/gui/helper/ProxyUtils.java // public class ProxyUtils // { // private static final Logger logger = Logger.getLogger(ProxyUtils.class.getName()); // private static final String USE_SYSTEM_PROXIES = "java.net.useSystemProxies"; // private static final String PROXY_TEST_URL = "http://trust-ws.services.belgium.be/eid-trust-service-ws/xkms2"; // private static final Proxy systemProxy =determineSystemProxy(PROXY_TEST_URL); // // public static Proxy getSystemProxy() // { // if(systemProxy==null) // return Proxy.NO_PROXY; // return systemProxy; // } // // public static String getHostName(Proxy proxy) // { // InetSocketAddress address=(InetSocketAddress) proxy.address(); // return address.getHostName(); // } // // public static int getPort(Proxy proxy) // { // InetSocketAddress address=(InetSocketAddress) proxy.address(); // return address.getPort(); // } // // private static Proxy determineSystemProxy(String forURL) // { // Proxy newProxy=Proxy.NO_PROXY; // // logger.log(Level.FINEST, "Determining System Proxy For[{0}]", forURL); // // final String savedProxySetting = System.getProperty(USE_SYSTEM_PROXIES); // logger.finest("Saved Original useSystemProxies Setting"); // // try // { // logger.finest("Temporarily Enabling useSystemProxies"); // System.setProperty(USE_SYSTEM_PROXIES,"true"); // logger.log(Level.FINEST, "using default ProxySelector on [{0}]", forURL); // List<Proxy> availableProxies=ProxySelector.getDefault().select(new java.net.URI(PROXY_TEST_URL)); // logger.log(Level.FINEST, "Default ProxySelector returned [{0}] Proxy Objects", availableProxies.size()); // // logger.finest("Finding HTTP Proxies"); // for(Proxy proxy : availableProxies) // try HTTP proxies // { // logger.log(Level.FINEST, "Checking Out [{0}]", proxy.toString()); // if(proxy.type().equals(Proxy.Type.HTTP)) // { // logger.log(Level.FINEST, "Found HTTP Connection [{0}]", proxy.toString()); // newProxy=proxy; // break; // } // } // // } // catch(Exception e) // { // logger.log(Level.WARNING,"Cannot Determine System HTTP Proxy", e); // } // finally // { // if(savedProxySetting!=null) // { // logger.finest("Restoring Enabling useSystemProxies"); // System.setProperty(USE_SYSTEM_PROXIES, savedProxySetting); // } // } // // return newProxy; // } // }
import be.fedict.eidviewer.gui.helper.ProxyUtils; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences;
return getDefaultLocale(); String language = prefs.get(LOCALE_LANGUAGE, DEFAULT_LOCALE_LANGUAGE); if (language == null) return getDefaultLocale(); if (isLanguageBelgian(language)) return new Locale(language, "BE"); else return Locale.US; } public static String getFullVersion() { return "eID Viewer " + getVersion(); } public static String getVersion() { ResourceBundle bundle = ResourceBundle .getBundle("be/fedict/eidviewer/gui/resources/Version"); return bundle.getString("version"); } public static Proxy getProxy() { validateProxy(); switch (getProxyType()) { case PROXY_SPECIFIC: return new Proxy(Proxy.Type.HTTP, new InetSocketAddress( getSpecificProxyHost(), getSpecificProxyPort())); case PROXY_SYSTEM:
// Path: eid-viewer-gui/src/main/java/be/fedict/eidviewer/gui/helper/ProxyUtils.java // public class ProxyUtils // { // private static final Logger logger = Logger.getLogger(ProxyUtils.class.getName()); // private static final String USE_SYSTEM_PROXIES = "java.net.useSystemProxies"; // private static final String PROXY_TEST_URL = "http://trust-ws.services.belgium.be/eid-trust-service-ws/xkms2"; // private static final Proxy systemProxy =determineSystemProxy(PROXY_TEST_URL); // // public static Proxy getSystemProxy() // { // if(systemProxy==null) // return Proxy.NO_PROXY; // return systemProxy; // } // // public static String getHostName(Proxy proxy) // { // InetSocketAddress address=(InetSocketAddress) proxy.address(); // return address.getHostName(); // } // // public static int getPort(Proxy proxy) // { // InetSocketAddress address=(InetSocketAddress) proxy.address(); // return address.getPort(); // } // // private static Proxy determineSystemProxy(String forURL) // { // Proxy newProxy=Proxy.NO_PROXY; // // logger.log(Level.FINEST, "Determining System Proxy For[{0}]", forURL); // // final String savedProxySetting = System.getProperty(USE_SYSTEM_PROXIES); // logger.finest("Saved Original useSystemProxies Setting"); // // try // { // logger.finest("Temporarily Enabling useSystemProxies"); // System.setProperty(USE_SYSTEM_PROXIES,"true"); // logger.log(Level.FINEST, "using default ProxySelector on [{0}]", forURL); // List<Proxy> availableProxies=ProxySelector.getDefault().select(new java.net.URI(PROXY_TEST_URL)); // logger.log(Level.FINEST, "Default ProxySelector returned [{0}] Proxy Objects", availableProxies.size()); // // logger.finest("Finding HTTP Proxies"); // for(Proxy proxy : availableProxies) // try HTTP proxies // { // logger.log(Level.FINEST, "Checking Out [{0}]", proxy.toString()); // if(proxy.type().equals(Proxy.Type.HTTP)) // { // logger.log(Level.FINEST, "Found HTTP Connection [{0}]", proxy.toString()); // newProxy=proxy; // break; // } // } // // } // catch(Exception e) // { // logger.log(Level.WARNING,"Cannot Determine System HTTP Proxy", e); // } // finally // { // if(savedProxySetting!=null) // { // logger.finest("Restoring Enabling useSystemProxies"); // System.setProperty(USE_SYSTEM_PROXIES, savedProxySetting); // } // } // // return newProxy; // } // } // Path: eid-viewer-gui/src/main/java/be/fedict/eidviewer/gui/ViewerPrefs.java import be.fedict.eidviewer.gui.helper.ProxyUtils; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; return getDefaultLocale(); String language = prefs.get(LOCALE_LANGUAGE, DEFAULT_LOCALE_LANGUAGE); if (language == null) return getDefaultLocale(); if (isLanguageBelgian(language)) return new Locale(language, "BE"); else return Locale.US; } public static String getFullVersion() { return "eID Viewer " + getVersion(); } public static String getVersion() { ResourceBundle bundle = ResourceBundle .getBundle("be/fedict/eidviewer/gui/resources/Version"); return bundle.getString("version"); } public static Proxy getProxy() { validateProxy(); switch (getProxyType()) { case PROXY_SPECIFIC: return new Proxy(Proxy.Type.HTTP, new InetSocketAddress( getSpecificProxyHost(), getSpecificProxyPort())); case PROXY_SYSTEM:
return ProxyUtils.getSystemProxy();
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/QueryResultTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for result set row counts. * * @author Antti Laisi */ public class QueryResultTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CONN_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows());
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/QueryResultTest.java import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for result set row counts. * * @author Antti Laisi */ public class QueryResultTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CONN_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows());
ResultSet result = dbr.query("SELECT * FROM CONN_TEST WHERE ID <= 2 ORDER BY ID");
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/QueryResultTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for result set row counts. * * @author Antti Laisi */ public class QueryResultTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CONN_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows()); ResultSet result = dbr.query("SELECT * FROM CONN_TEST WHERE ID <= 2 ORDER BY ID"); assertEquals(2, result.size()); Assert.assertEquals("ID", result.getOrderedColumns().iterator().next().getName().toUpperCase());
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/QueryResultTest.java import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for result set row counts. * * @author Antti Laisi */ public class QueryResultTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CONN_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows()); ResultSet result = dbr.query("SELECT * FROM CONN_TEST WHERE ID <= 2 ORDER BY ID"); assertEquals(2, result.size()); Assert.assertEquals("ID", result.getOrderedColumns().iterator().next().getName().toUpperCase());
Iterator<Row> i = result.iterator();
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/QueryResultTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals;
@AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows()); ResultSet result = dbr.query("SELECT * FROM CONN_TEST WHERE ID <= 2 ORDER BY ID"); assertEquals(2, result.size()); Assert.assertEquals("ID", result.getOrderedColumns().iterator().next().getName().toUpperCase()); Iterator<Row> i = result.iterator(); assertEquals(1L, i.next().getLong(0).longValue()); assertEquals(2L, i.next().getLong(0).longValue()); } @Test public void shouldReturnDeletedRowsCount() { Assert.assertEquals(1, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (3)").affectedRows()); Assert.assertEquals(1, dbr.query("DELETE FROM CONN_TEST WHERE ID = 3").affectedRows()); } @Test public void shouldReturnUpdatedRowsCount() { Assert.assertEquals(3, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (9),(10),(11)").affectedRows()); Assert.assertEquals(3, dbr.query("UPDATE CONN_TEST SET ID = NULL WHERE ID IN (9,10,11)").affectedRows()); }
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/QueryResultTest.java import com.pgasync.ResultSet; import com.pgasync.Row; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CONN_TEST"); } @Test public void shouldReturnResultSetSize() { Assert.assertEquals(2, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (1),(2)").affectedRows()); ResultSet result = dbr.query("SELECT * FROM CONN_TEST WHERE ID <= 2 ORDER BY ID"); assertEquals(2, result.size()); Assert.assertEquals("ID", result.getOrderedColumns().iterator().next().getName().toUpperCase()); Iterator<Row> i = result.iterator(); assertEquals(1L, i.next().getLong(0).longValue()); assertEquals(2L, i.next().getLong(0).longValue()); } @Test public void shouldReturnDeletedRowsCount() { Assert.assertEquals(1, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (3)").affectedRows()); Assert.assertEquals(1, dbr.query("DELETE FROM CONN_TEST WHERE ID = 3").affectedRows()); } @Test public void shouldReturnUpdatedRowsCount() { Assert.assertEquals(3, dbr.query("INSERT INTO CONN_TEST (ID) VALUES (9),(10),(11)").affectedRows()); Assert.assertEquals(3, dbr.query("UPDATE CONN_TEST SET ID = NULL WHERE ID IN (9,10,11)").affectedRows()); }
@Test(expected = SqlException.class)
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/DescribeEncoder.java
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Describe.java // public class Describe implements ExtendedQueryMessage { // // public enum Kind { // STATEMENT((byte) 'S'), // PORTAL((byte) 'P'); // // byte code; // // Kind(byte code) { // this.code = code; // } // // public byte getCode() { // return code; // } // } // // private final Kind kind; // private final String name; // // Describe(String name, Kind kind) { // this.name = name; // this.kind = kind; // } // // public Kind getKind() { // return kind; // } // // public String getName() { // return name; // } // // public static Describe portal() { // return new Describe("", Kind.PORTAL); // } // // public static Describe statement(String name) { // return new Describe(name, Kind.STATEMENT); // } // }
import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Describe; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Describe (F) * Byte1('D') * Identifies the message as a Describe command. * * Int32 * Length of message contents in bytes, including self. * * Byte1 * 'S' to describe a prepared statement; or 'P' to describe a portal. * * String * The name of the prepared statement or portal to describe (an empty string selects the unnamed prepared statement or portal). * *</pre> * * @author Marat Gainullin */ public class DescribeEncoder extends ExtendedQueryEncoder<Describe> { @Override public Class<Describe> getMessageType() { return Describe.class; } @Override protected byte getMessageId() { return (byte) 'D'; } @Override public void writeBody(Describe msg, ByteBuffer buffer, Charset encoding) { // Describe buffer.put(msg.getKind().getCode());
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Describe.java // public class Describe implements ExtendedQueryMessage { // // public enum Kind { // STATEMENT((byte) 'S'), // PORTAL((byte) 'P'); // // byte code; // // Kind(byte code) { // this.code = code; // } // // public byte getCode() { // return code; // } // } // // private final Kind kind; // private final String name; // // Describe(String name, Kind kind) { // this.name = name; // this.kind = kind; // } // // public Kind getKind() { // return kind; // } // // public String getName() { // return name; // } // // public static Describe portal() { // return new Describe("", Kind.PORTAL); // } // // public static Describe statement(String name) { // return new Describe(name, Kind.STATEMENT); // } // } // Path: src/main/java/com/github/pgasync/io/frontend/DescribeEncoder.java import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Describe; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Describe (F) * Byte1('D') * Identifies the message as a Describe command. * * Int32 * Length of message contents in bytes, including self. * * Byte1 * 'S' to describe a prepared statement; or 'P' to describe a portal. * * String * The name of the prepared statement or portal to describe (an empty string selects the unnamed prepared statement or portal). * *</pre> * * @author Marat Gainullin */ public class DescribeEncoder extends ExtendedQueryEncoder<Describe> { @Override public Class<Describe> getMessageType() { return Describe.class; } @Override protected byte getMessageId() { return (byte) 'D'; } @Override public void writeBody(Describe msg, ByteBuffer buffer, Charset encoding) { // Describe buffer.put(msg.getKind().getCode());
IO.putCString(buffer, msg.getName(), encoding);
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ValidatedConnectionTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for validated connections. * * @author Marat Gainullin */ public class ValidatedConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule();
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/ValidatedConnectionTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for validated connections. * * @author Marat Gainullin */ public class ValidatedConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule();
private void withSource(Connectible source, Consumer<Connectible> action) throws Exception {
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ValidatedConnectionTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for validated connections. * * @author Marat Gainullin */ public class ValidatedConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule(); private void withSource(Connectible source, Consumer<Connectible> action) throws Exception { try { action.accept(source); } catch (Exception ex) {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/ValidatedConnectionTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for validated connections. * * @author Marat Gainullin */ public class ValidatedConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule(); private void withSource(Connectible source, Consumer<Connectible> action) throws Exception { try { action.accept(source); } catch (Exception ex) {
SqlException.ifCause(ex,
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ValidatedConnectionTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer;
sqlException -> { throw sqlException; }, () -> { throw ex; }); } finally { source.close().join(); } } private void withPlain(String clause, Consumer<Connectible> action) throws Exception { withSource(dbr.builder .validationQuery(clause) .plain(), action ); } private void withPool(String clause, Consumer<Connectible> action) throws Exception { withSource(dbr.builder .validationQuery(clause) .pool(), action ); } @Test public void shouldReturnValidPlainConnection() throws Exception { withPlain("Select 89", plain -> {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/ValidatedConnectionTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.Rule; import org.junit.Test; import java.util.function.Consumer; sqlException -> { throw sqlException; }, () -> { throw ex; }); } finally { source.close().join(); } } private void withPlain(String clause, Consumer<Connectible> action) throws Exception { withSource(dbr.builder .validationQuery(clause) .plain(), action ); } private void withPool(String clause, Consumer<Connectible> action) throws Exception { withSource(dbr.builder .validationQuery(clause) .pool(), action ); } @Test public void shouldReturnValidPlainConnection() throws Exception { withPlain("Select 89", plain -> {
Connection conn = plain.getConnection().join();
alaisi/postgres-async-driver
src/main/java/com/pgasync/Converter.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.github.pgasync.Oid;
package com.pgasync; /** * Converters extend the driver to handle complex data types, * for example json or hstore that have no "standard" Java * representation. * * @author Antti Laisi. */ public interface Converter<T> { /** * @return Class to convert */ Class<T> type(); /** * @param o Object to convert, never null * @return data in backend format */ String from(T o); /** * @param oid Value oid * @param value Value in backend format, never null * @return Converted object, never null */
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/pgasync/Converter.java import com.github.pgasync.Oid; package com.pgasync; /** * Converters extend the driver to handle complex data types, * for example json or hstore that have no "standard" Java * representation. * * @author Antti Laisi. */ public interface Converter<T> { /** * @return Class to convert */ Class<T> type(); /** * @param o Object to convert, never null * @return data in backend format */ String from(T o); /** * @param oid Value oid * @param value Value in backend format, never null * @return Converted object, never null */
T to(Oid oid, String value);
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/ArrayConversions.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.github.pgasync.Oid; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function;
} Object o = Array.get(elements, i); if (o == null) { sb.append("NULL"); } else if (o instanceof byte[]) { sb.append(BlobConversions.fromBytes((byte[]) o)); } else if (o.getClass().isArray()) { sb = appendArray(sb, o, printFn); } else { sb = appendEscaped(sb, printFn.apply(o)); } } return sb.append('}'); } private static StringBuilder appendEscaped(final StringBuilder b, final String s) { b.append('"'); for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (c == '"' || c == '\\') { b.append('\\'); } b.append(c); } return b.append('"'); }
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/ArrayConversions.java import com.github.pgasync.Oid; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; } Object o = Array.get(elements, i); if (o == null) { sb.append("NULL"); } else if (o instanceof byte[]) { sb.append(BlobConversions.fromBytes((byte[]) o)); } else if (o.getClass().isArray()) { sb = appendArray(sb, o, printFn); } else { sb = appendEscaped(sb, printFn.apply(o)); } } return sb.append('}'); } private static StringBuilder appendEscaped(final StringBuilder b, final String s) { b.append('"'); for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (c == '"' || c == '\\') { b.append('\\'); } b.append(c); } return b.append('"'); }
static <T> T toArray(Class<T> arrayType, Oid oid, String value, BiFunction<Oid, String, Object> parse) {
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/CustomConverterTest.java
// Path: src/main/java/com/pgasync/Converter.java // public interface Converter<T> { // // /** // * @return Class to convert // */ // Class<T> type(); // // /** // * @param o Object to convert, never null // * @return data in backend format // */ // String from(T o); // // /** // * @param oid Value oid // * @param value Value in backend format, never null // * @return Converted object, never null // */ // T to(Oid oid, String value); // // }
import com.pgasync.Converter; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals;
package com.github.pgasync; /** * @author Antti Laisi */ public class CustomConverterTest { static class Json { final String json; Json(String json) { this.json = json; } }
// Path: src/main/java/com/pgasync/Converter.java // public interface Converter<T> { // // /** // * @return Class to convert // */ // Class<T> type(); // // /** // * @param o Object to convert, never null // * @return data in backend format // */ // String from(T o); // // /** // * @param oid Value oid // * @param value Value in backend format, never null // * @return Converted object, never null // */ // T to(Oid oid, String value); // // } // Path: src/test/java/com/github/pgasync/CustomConverterTest.java import com.pgasync.Converter; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; package com.github.pgasync; /** * @author Antti Laisi */ public class CustomConverterTest { static class Json { final String json; Json(String json) { this.json = json; } }
static class JsonConverter implements Converter<Json> {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/BindEncoder.java
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Bind.java // public class Bind implements ExtendedQueryMessage { // // private final String sname; // private final byte[][] params; // // public Bind(String sname, byte[][] params) { // this.sname = sname; // this.params = params; // } // // public String getSname() { // return sname; // } // // public byte[][] getParams() { // return params; // } // }
import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Bind; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Bind (F) * Byte1('B') * Identifies the message as a Bind command. * * Int32 * Length of message contents in bytes, including self. * * String * The name of the destination portal (an empty string selects the unnamed portal). * * String * The name of the source prepared statement (an empty string selects the unnamed prepared statement). * * Int16 * The number of parameter format codes that follow (denoted C below). This can be zero to indicate that there are no parameters or that the parameters all use the default format (text); or one, in which case the specified format code is applied to all parameters; or it can equal the actual number of parameters. * * Int16[C] * The parameter format codes. Each must presently be zero (text) or one (binary). * * Int16 * The number of parameter values that follow (possibly zero). This must match the number of parameters needed by the query. * * Next, the following pair of fields appear for each parameter: * * Int32 * The length of the parameter value, in bytes (this count does not include itself). Can be zero. As a special case, -1 indicates a NULL parameter value. No value bytes follow in the NULL case. * * Byten * The value of the parameter, in the format indicated by the associated format code. n is the above length. * * After the last parameter, the following fields appear: * * Int16 * The number of result-column format codes that follow (denoted R below). This can be zero to indicate that there are no result columns or that the result columns should all use the default format (text); or one, in which case the specified format code is applied to all result columns (if any); or it can equal the actual number of result columns of the query. * * Int16[R] * The result-column format codes. Each must presently be zero (text) or one (binary). * </pre> * * @author Antti Laisi */ public class BindEncoder extends ExtendedQueryEncoder<Bind> { @Override public Class<Bind> getMessageType() { return Bind.class; } @Override protected byte getMessageId() { return (byte) 'B'; } @Override public void writeBody(Bind msg, ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Bind.java // public class Bind implements ExtendedQueryMessage { // // private final String sname; // private final byte[][] params; // // public Bind(String sname, byte[][] params) { // this.sname = sname; // this.params = params; // } // // public String getSname() { // return sname; // } // // public byte[][] getParams() { // return params; // } // } // Path: src/main/java/com/github/pgasync/io/frontend/BindEncoder.java import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Bind; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Bind (F) * Byte1('B') * Identifies the message as a Bind command. * * Int32 * Length of message contents in bytes, including self. * * String * The name of the destination portal (an empty string selects the unnamed portal). * * String * The name of the source prepared statement (an empty string selects the unnamed prepared statement). * * Int16 * The number of parameter format codes that follow (denoted C below). This can be zero to indicate that there are no parameters or that the parameters all use the default format (text); or one, in which case the specified format code is applied to all parameters; or it can equal the actual number of parameters. * * Int16[C] * The parameter format codes. Each must presently be zero (text) or one (binary). * * Int16 * The number of parameter values that follow (possibly zero). This must match the number of parameters needed by the query. * * Next, the following pair of fields appear for each parameter: * * Int32 * The length of the parameter value, in bytes (this count does not include itself). Can be zero. As a special case, -1 indicates a NULL parameter value. No value bytes follow in the NULL case. * * Byten * The value of the parameter, in the format indicated by the associated format code. n is the above length. * * After the last parameter, the following fields appear: * * Int16 * The number of result-column format codes that follow (denoted R below). This can be zero to indicate that there are no result columns or that the result columns should all use the default format (text); or one, in which case the specified format code is applied to all result columns (if any); or it can equal the actual number of result columns of the query. * * Int16[R] * The result-column format codes. Each must presently be zero (text) or one (binary). * </pre> * * @author Antti Laisi */ public class BindEncoder extends ExtendedQueryEncoder<Bind> { @Override public Class<Bind> getMessageType() { return Bind.class; } @Override protected byte getMessageId() { return (byte) 'B'; } @Override public void writeBody(Bind msg, ByteBuffer buffer, Charset encoding) {
IO.putCString(buffer, "", encoding); // portal
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/ParseEncoder.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/frontend/Parse.java // public class Parse implements ExtendedQueryMessage { // // private final String sql; // private final String sname; // private final Oid[] types; // // public Parse(String sql, String sname, Oid[] types) { // this.sql = sql; // this.sname = sname; // this.types = types; // } // // public String getQuery() { // return sql; // } // // public String getSname() { // return sname; // } // // public Oid[] getTypes() { // return types; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.Oid; import com.github.pgasync.message.frontend.Parse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Parse (F) * Byte1('P') * Identifies the message as a Parse command. * Int32 * Length of message contents in bytes, including self. * String * The name of the destination prepared statement (an empty string selects the unnamed prepared statement). * String * The query string to be parsed. * Int16 * The number of parameter data types specified (can be zero). Note that this is not an indication of the number of parameters that might appear in the query string, only the number that the frontend wants to prespecify types for. * Then, for each parameter, there is the following: * Int32 * Specifies the object ID of the parameter data type. Placing a zero here is equivalent to leaving the type unspecified. * </pre> * * @author Antti Laisi */ public class ParseEncoder extends ExtendedQueryEncoder<Parse> { @Override public Class<Parse> getMessageType() { return Parse.class; } @Override protected byte getMessageId() { return (byte) 'P'; } @Override public void writeBody(Parse msg, ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/frontend/Parse.java // public class Parse implements ExtendedQueryMessage { // // private final String sql; // private final String sname; // private final Oid[] types; // // public Parse(String sql, String sname, Oid[] types) { // this.sql = sql; // this.sname = sname; // this.types = types; // } // // public String getQuery() { // return sql; // } // // public String getSname() { // return sname; // } // // public Oid[] getTypes() { // return types; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/frontend/ParseEncoder.java import com.github.pgasync.Oid; import com.github.pgasync.message.frontend.Parse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Parse (F) * Byte1('P') * Identifies the message as a Parse command. * Int32 * Length of message contents in bytes, including self. * String * The name of the destination prepared statement (an empty string selects the unnamed prepared statement). * String * The query string to be parsed. * Int16 * The number of parameter data types specified (can be zero). Note that this is not an indication of the number of parameters that might appear in the query string, only the number that the frontend wants to prespecify types for. * Then, for each parameter, there is the following: * Int32 * Specifies the object ID of the parameter data type. Placing a zero here is equivalent to leaving the type unspecified. * </pre> * * @author Antti Laisi */ public class ParseEncoder extends ExtendedQueryEncoder<Parse> { @Override public Class<Parse> getMessageType() { return Parse.class; } @Override protected byte getMessageId() { return (byte) 'P'; } @Override public void writeBody(Parse msg, ByteBuffer buffer, Charset encoding) {
IO.putCString(buffer, msg.getSname(), encoding); // prepared statement
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/ParseEncoder.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/frontend/Parse.java // public class Parse implements ExtendedQueryMessage { // // private final String sql; // private final String sname; // private final Oid[] types; // // public Parse(String sql, String sname, Oid[] types) { // this.sql = sql; // this.sname = sname; // this.types = types; // } // // public String getQuery() { // return sql; // } // // public String getSname() { // return sname; // } // // public Oid[] getTypes() { // return types; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.Oid; import com.github.pgasync.message.frontend.Parse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Parse (F) * Byte1('P') * Identifies the message as a Parse command. * Int32 * Length of message contents in bytes, including self. * String * The name of the destination prepared statement (an empty string selects the unnamed prepared statement). * String * The query string to be parsed. * Int16 * The number of parameter data types specified (can be zero). Note that this is not an indication of the number of parameters that might appear in the query string, only the number that the frontend wants to prespecify types for. * Then, for each parameter, there is the following: * Int32 * Specifies the object ID of the parameter data type. Placing a zero here is equivalent to leaving the type unspecified. * </pre> * * @author Antti Laisi */ public class ParseEncoder extends ExtendedQueryEncoder<Parse> { @Override public Class<Parse> getMessageType() { return Parse.class; } @Override protected byte getMessageId() { return (byte) 'P'; } @Override public void writeBody(Parse msg, ByteBuffer buffer, Charset encoding) { IO.putCString(buffer, msg.getSname(), encoding); // prepared statement IO.putCString(buffer, msg.getQuery(), encoding); buffer.putShort((short) msg.getTypes().length); // parameter types count
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/frontend/Parse.java // public class Parse implements ExtendedQueryMessage { // // private final String sql; // private final String sname; // private final Oid[] types; // // public Parse(String sql, String sname, Oid[] types) { // this.sql = sql; // this.sname = sname; // this.types = types; // } // // public String getQuery() { // return sql; // } // // public String getSname() { // return sname; // } // // public Oid[] getTypes() { // return types; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/frontend/ParseEncoder.java import com.github.pgasync.Oid; import com.github.pgasync.message.frontend.Parse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Parse (F) * Byte1('P') * Identifies the message as a Parse command. * Int32 * Length of message contents in bytes, including self. * String * The name of the destination prepared statement (an empty string selects the unnamed prepared statement). * String * The query string to be parsed. * Int16 * The number of parameter data types specified (can be zero). Note that this is not an indication of the number of parameters that might appear in the query string, only the number that the frontend wants to prespecify types for. * Then, for each parameter, there is the following: * Int32 * Specifies the object ID of the parameter data type. Placing a zero here is equivalent to leaving the type unspecified. * </pre> * * @author Antti Laisi */ public class ParseEncoder extends ExtendedQueryEncoder<Parse> { @Override public Class<Parse> getMessageType() { return Parse.class; } @Override protected byte getMessageId() { return (byte) 'P'; } @Override public void writeBody(Parse msg, ByteBuffer buffer, Charset encoding) { IO.putCString(buffer, msg.getSname(), encoding); // prepared statement IO.putCString(buffer, msg.getQuery(), encoding); buffer.putShort((short) msg.getTypes().length); // parameter types count
for (Oid type : msg.getTypes()) {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/TemporalConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;
package com.github.pgasync.conversion; /** * @author Antti Laisi * <p> * TODO: Add support for Java 8 temporal types. */ class TemporalConversions { private static final DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .toFormatter(); private static final DateTimeFormatter TIMESTAMPZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); private static final DateTimeFormatter TIMEZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter();
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/TemporalConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; package com.github.pgasync.conversion; /** * @author Antti Laisi * <p> * TODO: Add support for Java 8 temporal types. */ class TemporalConversions { private static final DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .toFormatter(); private static final DateTimeFormatter TIMESTAMPZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); private static final DateTimeFormatter TIMEZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter();
static Date toDate(Oid oid, String value) {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/TemporalConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;
package com.github.pgasync.conversion; /** * @author Antti Laisi * <p> * TODO: Add support for Java 8 temporal types. */ class TemporalConversions { private static final DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .toFormatter(); private static final DateTimeFormatter TIMESTAMPZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); private static final DateTimeFormatter TIMEZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); static Date toDate(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case DATE: try { return Date.valueOf(LocalDate.parse(value, ISO_LOCAL_DATE)); } catch (DateTimeParseException e) {
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/TemporalConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; package com.github.pgasync.conversion; /** * @author Antti Laisi * <p> * TODO: Add support for Java 8 temporal types. */ class TemporalConversions { private static final DateTimeFormatter TIMESTAMP_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .toFormatter(); private static final DateTimeFormatter TIMESTAMPZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral(' ') .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); private static final DateTimeFormatter TIMEZ_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(ISO_LOCAL_TIME) .appendOffset("+HH:mm", "") .toFormatter(); static Date toDate(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case DATE: try { return Date.valueOf(LocalDate.parse(value, ISO_LOCAL_DATE)); } catch (DateTimeParseException e) {
throw new SqlException("Invalid date: " + value);
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ListenNotifyTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*;
package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5));
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // } // Path: src/test/java/com/github/pgasync/ListenNotifyTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5));
private Connectible pool;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ListenNotifyTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*;
package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldReceiveNotificationsOnListenedChannel() throws InterruptedException { BlockingQueue<String> result = new LinkedBlockingQueue<>(5);
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // } // Path: src/test/java/com/github/pgasync/ListenNotifyTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldReceiveNotificationsOnListenedChannel() throws InterruptedException { BlockingQueue<String> result = new LinkedBlockingQueue<>(5);
Connection conn = pool.getConnection().join();
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ListenNotifyTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*;
package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldReceiveNotificationsOnListenedChannel() throws InterruptedException { BlockingQueue<String> result = new LinkedBlockingQueue<>(5); Connection conn = pool.getConnection().join(); try {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Listening.java // @FunctionalInterface // public interface Listening { // // CompletableFuture<Void> unlisten(); // } // Path: src/test/java/com/github/pgasync/ListenNotifyTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.Listening; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; package com.github.pgasync; /** * @author Antti Laisi */ public class ListenNotifyTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldReceiveNotificationsOnListenedChannel() throws InterruptedException { BlockingQueue<String> result = new LinkedBlockingQueue<>(5); Connection conn = pool.getConnection().join(); try {
Listening subscription = conn.subscribe("example", result::offer).join();
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test;
package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5));
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // } // Path: src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5));
private Connectible pool;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test;
package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.builder .maxConnections(1) .maxStatements(1) .pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldEvictedStatementBeReallyClosed() {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // } // Path: src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.builder .maxConnections(1) .maxStatements(1) .pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldEvictedStatementBeReallyClosed() {
Connection conn = pool.getConnection().join();
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // }
import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test;
package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.builder .maxConnections(1) .maxStatements(1) .pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldEvictedStatementBeReallyClosed() { Connection conn = pool.getConnection().join(); try {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/PreparedStatement.java // public interface PreparedStatement { // // /** // * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. // * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. // * // * @param params Array of query parameters values. // * @return An instance of {@link ResultSet} with data. // */ // CompletableFuture<ResultSet> query(Object... params); // // /** // * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. // * // * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. // * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message // * to {@link Row} implementation instance. // * @param params Array of query parameters values. // * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. // */ // CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params); // // /** // * Closes this {@link PreparedStatement} and possibly frees resources. In case of pool statement it may be returned to a pool for future reuse. // * @return CompletableFuture that is completed when the network process ends. // * Network process may occur if returned statement has evicted some other statement from the pool in case of pooled statement. // * Closing of such evicted statement is network activity, we should be aware of. // */ // CompletableFuture<Void> close(); // // } // Path: src/test/java/com/github/pgasync/PreparedStatementsCacheTest.java import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.PreparedStatement; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; package com.github.pgasync; /** * @author Marat Gainullin */ public class PreparedStatementsCacheTest { private static final String SELECT_52 = "select 52"; private static final String SELECT_32 = "select 32"; @ClassRule public static DatabaseRule dbr = new DatabaseRule(DatabaseRule.createPoolBuilder(5)); private Connectible pool; @Before public void setup() { pool = dbr.builder .maxConnections(1) .maxStatements(1) .pool(); } @After public void shutdown() { pool.close().join(); } @Test public void shouldEvictedStatementBeReallyClosed() { Connection conn = pool.getConnection().join(); try {
PreparedStatement evictor = conn.prepareStatement(SELECT_52).join();
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/backend/CommandCompleteDecoder.java
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/CommandComplete.java // public class CommandComplete implements Message { // // private final int affectedRows; // // public CommandComplete(String tag) { // if (tag.contains("INSERT") || tag.contains("UPDATE") || tag.contains("DELETE")) { // String[] parts = tag.split(" "); // affectedRows = Integer.parseInt(parts[parts.length - 1]); // } else { // affectedRows = 0; // } // } // // public int getAffectedRows() { // return affectedRows; // } // // @Override // public String toString() { // return String.format("CommandComplete(affectedRows=%d)", affectedRows); // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // }
import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.CommandComplete; import java.nio.ByteBuffer; import java.nio.charset.Charset; import static com.github.pgasync.io.IO.getCString;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.backend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * CommandComplete (B) * Byte1('C') * Identifies the message as a command-completed response. * Int32 * Length of message contents in bytes, including self. * String * The command tag. This is usually a single word that identifies which SQL command was completed. * For an INSERT command, the tag is INSERT oid rows, where rows is the number of rows inserted. oid is the object ID of the inserted row if rows is 1 and the target table has OIDs; otherwise oid is 0. * For a DELETE command, the tag is DELETE rows where rows is the number of rows deleted. * For an UPDATE command, the tag is UPDATE rows where rows is the number of rows updated. * For a SELECT or CREATE TABLE AS command, the tag is SELECT rows where rows is the number of rows retrieved. * For a MOVE command, the tag is MOVE rows where rows is the number of rows the cursor's position has been changed by. * For a FETCH command, the tag is FETCH rows where rows is the number of rows that have been retrieved from the cursor. * For a COPY command, the tag is COPY rows where rows is the number of rows copied. (Note: the row count appears only in Postgres 8.2 and later.) * </pre> * * @author Antti Laisi */ public class CommandCompleteDecoder implements Decoder<CommandComplete> { @Override public byte getMessageId() { return 'C'; } @Override public CommandComplete read(ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/CommandComplete.java // public class CommandComplete implements Message { // // private final int affectedRows; // // public CommandComplete(String tag) { // if (tag.contains("INSERT") || tag.contains("UPDATE") || tag.contains("DELETE")) { // String[] parts = tag.split(" "); // affectedRows = Integer.parseInt(parts[parts.length - 1]); // } else { // affectedRows = 0; // } // } // // public int getAffectedRows() { // return affectedRows; // } // // @Override // public String toString() { // return String.format("CommandComplete(affectedRows=%d)", affectedRows); // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // Path: src/main/java/com/github/pgasync/io/backend/CommandCompleteDecoder.java import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.CommandComplete; import java.nio.ByteBuffer; import java.nio.charset.Charset; import static com.github.pgasync.io.IO.getCString; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.backend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * CommandComplete (B) * Byte1('C') * Identifies the message as a command-completed response. * Int32 * Length of message contents in bytes, including self. * String * The command tag. This is usually a single word that identifies which SQL command was completed. * For an INSERT command, the tag is INSERT oid rows, where rows is the number of rows inserted. oid is the object ID of the inserted row if rows is 1 and the target table has OIDs; otherwise oid is 0. * For a DELETE command, the tag is DELETE rows where rows is the number of rows deleted. * For an UPDATE command, the tag is UPDATE rows where rows is the number of rows updated. * For a SELECT or CREATE TABLE AS command, the tag is SELECT rows where rows is the number of rows retrieved. * For a MOVE command, the tag is MOVE rows where rows is the number of rows the cursor's position has been changed by. * For a FETCH command, the tag is FETCH rows where rows is the number of rows that have been retrieved from the cursor. * For a COPY command, the tag is COPY rows where rows is the number of rows copied. (Note: the row count appears only in Postgres 8.2 and later.) * </pre> * * @author Antti Laisi */ public class CommandCompleteDecoder implements Decoder<CommandComplete> { @Override public byte getMessageId() { return 'C'; } @Override public CommandComplete read(ByteBuffer buffer, Charset encoding) {
String tag = getCString(buffer, encoding);
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/BooleanConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BooleanConversions { private static final String TRUE = "t"; private static final String FALSE = "f";
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/BooleanConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BooleanConversions { private static final String TRUE = "t"; private static final String FALSE = "f";
static boolean toBoolean(Oid oid, String value) {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/BooleanConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BooleanConversions { private static final String TRUE = "t"; private static final String FALSE = "f"; static boolean toBoolean(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case BOOL: return TRUE.equals(value); default:
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/BooleanConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BooleanConversions { private static final String TRUE = "t"; private static final String FALSE = "f"; static boolean toBoolean(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case BOOL: return TRUE.equals(value); default:
throw new SqlException("Unsupported conversion " + oid.name() + " -> boolean");
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/backend/NotificationResponseDecoder.java
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/NotificationResponse.java // public class NotificationResponse implements Message { // // private final int backend; // private final String channel; // private final String payload; // // public NotificationResponse(int backend, String channel, String payload) { // this.backend = backend; // this.channel = channel; // this.payload = payload; // } // // public String getChannel() { // return channel; // } // // public String getPayload() { // return payload; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.NotificationResponse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset;
package com.github.pgasync.io.backend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * NotificationResponse (B) * Byte1('A') * Identifies the message as a notification response. * Int32 * Length of message contents in bytes, including self. * Int32 * The process ID of the notifying backend process. * String * The name of the channel that the notify has been raised on. * String * The "payload" string passed from the notifying process. * </pre> * * @author Antti Laisi */ public class NotificationResponseDecoder implements Decoder<NotificationResponse> { @Override public NotificationResponse read(ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/NotificationResponse.java // public class NotificationResponse implements Message { // // private final int backend; // private final String channel; // private final String payload; // // public NotificationResponse(int backend, String channel, String payload) { // this.backend = backend; // this.channel = channel; // this.payload = payload; // } // // public String getChannel() { // return channel; // } // // public String getPayload() { // return payload; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/backend/NotificationResponseDecoder.java import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.NotificationResponse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; package com.github.pgasync.io.backend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * NotificationResponse (B) * Byte1('A') * Identifies the message as a notification response. * Int32 * Length of message contents in bytes, including self. * Int32 * The process ID of the notifying backend process. * String * The name of the channel that the notify has been raised on. * String * The "payload" string passed from the notifying process. * </pre> * * @author Antti Laisi */ public class NotificationResponseDecoder implements Decoder<NotificationResponse> { @Override public NotificationResponse read(ByteBuffer buffer, Charset encoding) {
return new NotificationResponse(buffer.getInt(), IO.getCString(buffer, encoding), IO.getCString(buffer, encoding));
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PlainConnectionTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // }
import com.pgasync.Connectible; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for plain connection. * * @author Marat Gainullin */ public class PlainConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule();
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // Path: src/test/java/com/github/pgasync/PlainConnectionTest.java import com.pgasync.Connectible; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for plain connection. * * @author Marat Gainullin */ public class PlainConnectionTest { @Rule public final DatabaseRule dbr = new DatabaseRule();
private Connectible plain;
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/PgDatabase.java
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/NettyConnectibleBuilder.java // public class NettyConnectibleBuilder { // // private final ConnectibleProperties properties = new ConnectibleProperties(); // // TODO: refactor when Netty will support more advanced threading model // //new NioEventLoopGroup(0/*Netty defaults will be used*/, futuresExecutor), // private static final EventLoopGroup group = new NioEventLoopGroup(); // // private ProtocolStream newProtocolStream(Executor futuresExecutor) { // return new NettyProtocolStream( // group, // new InetSocketAddress(properties.getHostname(), properties.getPort()), // properties.getUseSsl(), // Charset.forName(properties.getEncoding()), // futuresExecutor // ); // } // // /** // * @return Pool ready for use // */ // public Connectible pool(Executor futuresExecutor) { // return new PgConnectionPool(properties, this::newProtocolStream, futuresExecutor); // } // // public Connectible pool() { // return pool(ForkJoinPool.commonPool()); // } // // // /** // * @return Pool ready for use // */ // public Connectible plain(Executor futuresExecutor) { // return new PgDatabase(properties, this::newProtocolStream, futuresExecutor); // } // // public Connectible plain() { // return plain(ForkJoinPool.commonPool()); // } // // public NettyConnectibleBuilder hostname(String hostname) { // properties.hostname = hostname; // return this; // } // // public NettyConnectibleBuilder port(int port) { // properties.port = port; // return this; // } // // public NettyConnectibleBuilder username(String username) { // properties.username = username; // return this; // } // // public NettyConnectibleBuilder password(String password) { // properties.password = password; // return this; // } // // public NettyConnectibleBuilder database(String database) { // properties.database = database; // return this; // } // // public NettyConnectibleBuilder maxConnections(int maxConnections) { // properties.maxConnections = maxConnections; // return this; // } // // public NettyConnectibleBuilder maxStatements(int maxStatements) { // properties.maxStatements = maxStatements; // return this; // } // // public NettyConnectibleBuilder converters(Converter<?>... converters) { // Collections.addAll(properties.converters, converters); // return this; // } // // public NettyConnectibleBuilder dataConverter(DataConverter dataConverter) { // properties.dataConverter = dataConverter; // return this; // } // // public NettyConnectibleBuilder ssl(boolean ssl) { // properties.useSsl = ssl; // return this; // } // // public NettyConnectibleBuilder validationQuery(String validationQuery) { // properties.validationQuery = validationQuery; // return this; // } // // public NettyConnectibleBuilder encoding(String value) { // properties.encoding = value; // return this; // } // // /** // * Configuration for a connectible. // */ // public static class ConnectibleProperties { // // String hostname = "localhost"; // int port = 5432; // String username; // String password; // String database; // int maxConnections = 20; // int maxStatements = 20; // DataConverter dataConverter; // List<Converter<?>> converters = new ArrayList<>(); // boolean useSsl; // String encoding = System.getProperty("pg.async.encoding", "utf-8"); // String validationQuery; // // public String getHostname() { // return hostname; // } // // public int getPort() { // return port; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // // public String getDatabase() { // return database; // } // // public int getMaxConnections() { // return maxConnections; // } // // public int getMaxStatements() { // return maxStatements; // } // // public boolean getUseSsl() { // return useSsl; // } // // public String getEncoding() { // return encoding; // } // // public DataConverter getDataConverter() { // return dataConverter != null ? dataConverter : new DataConverter(converters, Charset.forName(encoding)); // } // // public String getValidationQuery() { // return validationQuery; // } // } // }
import com.pgasync.Connection; import com.pgasync.NettyConnectibleBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.function.Function;
package com.github.pgasync; public class PgDatabase extends PgConnectible { public PgDatabase(NettyConnectibleBuilder.ConnectibleProperties properties, Function<Executor, ProtocolStream> toStream, Executor futuresExecutor) { super(properties, toStream, futuresExecutor); } @Override
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/NettyConnectibleBuilder.java // public class NettyConnectibleBuilder { // // private final ConnectibleProperties properties = new ConnectibleProperties(); // // TODO: refactor when Netty will support more advanced threading model // //new NioEventLoopGroup(0/*Netty defaults will be used*/, futuresExecutor), // private static final EventLoopGroup group = new NioEventLoopGroup(); // // private ProtocolStream newProtocolStream(Executor futuresExecutor) { // return new NettyProtocolStream( // group, // new InetSocketAddress(properties.getHostname(), properties.getPort()), // properties.getUseSsl(), // Charset.forName(properties.getEncoding()), // futuresExecutor // ); // } // // /** // * @return Pool ready for use // */ // public Connectible pool(Executor futuresExecutor) { // return new PgConnectionPool(properties, this::newProtocolStream, futuresExecutor); // } // // public Connectible pool() { // return pool(ForkJoinPool.commonPool()); // } // // // /** // * @return Pool ready for use // */ // public Connectible plain(Executor futuresExecutor) { // return new PgDatabase(properties, this::newProtocolStream, futuresExecutor); // } // // public Connectible plain() { // return plain(ForkJoinPool.commonPool()); // } // // public NettyConnectibleBuilder hostname(String hostname) { // properties.hostname = hostname; // return this; // } // // public NettyConnectibleBuilder port(int port) { // properties.port = port; // return this; // } // // public NettyConnectibleBuilder username(String username) { // properties.username = username; // return this; // } // // public NettyConnectibleBuilder password(String password) { // properties.password = password; // return this; // } // // public NettyConnectibleBuilder database(String database) { // properties.database = database; // return this; // } // // public NettyConnectibleBuilder maxConnections(int maxConnections) { // properties.maxConnections = maxConnections; // return this; // } // // public NettyConnectibleBuilder maxStatements(int maxStatements) { // properties.maxStatements = maxStatements; // return this; // } // // public NettyConnectibleBuilder converters(Converter<?>... converters) { // Collections.addAll(properties.converters, converters); // return this; // } // // public NettyConnectibleBuilder dataConverter(DataConverter dataConverter) { // properties.dataConverter = dataConverter; // return this; // } // // public NettyConnectibleBuilder ssl(boolean ssl) { // properties.useSsl = ssl; // return this; // } // // public NettyConnectibleBuilder validationQuery(String validationQuery) { // properties.validationQuery = validationQuery; // return this; // } // // public NettyConnectibleBuilder encoding(String value) { // properties.encoding = value; // return this; // } // // /** // * Configuration for a connectible. // */ // public static class ConnectibleProperties { // // String hostname = "localhost"; // int port = 5432; // String username; // String password; // String database; // int maxConnections = 20; // int maxStatements = 20; // DataConverter dataConverter; // List<Converter<?>> converters = new ArrayList<>(); // boolean useSsl; // String encoding = System.getProperty("pg.async.encoding", "utf-8"); // String validationQuery; // // public String getHostname() { // return hostname; // } // // public int getPort() { // return port; // } // // public String getUsername() { // return username; // } // // public String getPassword() { // return password; // } // // public String getDatabase() { // return database; // } // // public int getMaxConnections() { // return maxConnections; // } // // public int getMaxStatements() { // return maxStatements; // } // // public boolean getUseSsl() { // return useSsl; // } // // public String getEncoding() { // return encoding; // } // // public DataConverter getDataConverter() { // return dataConverter != null ? dataConverter : new DataConverter(converters, Charset.forName(encoding)); // } // // public String getValidationQuery() { // return validationQuery; // } // } // } // Path: src/main/java/com/github/pgasync/PgDatabase.java import com.pgasync.Connection; import com.pgasync.NettyConnectibleBuilder; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.function.Function; package com.github.pgasync; public class PgDatabase extends PgConnectible { public PgDatabase(NettyConnectibleBuilder.ConnectibleProperties properties, Function<Executor, ProtocolStream> toStream, Executor futuresExecutor) { super(properties, toStream, futuresExecutor); } @Override
public CompletableFuture<Connection> getConnection() {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/CloseEncoder.java
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Close.java // public class Close implements ExtendedQueryMessage { // // public enum Kind { // STATEMENT((byte) 'S'), // PORTAL((byte) 'P'); // // byte code; // // Kind(byte code) { // this.code = code; // } // // public byte getCode() { // return code; // } // } // // private final Kind kind; // private final String name; // // private Close(String name, Kind kind) { // this.name = name; // this.kind = kind; // } // // public String getName() { // return name; // } // // public Kind getKind() { // return kind; // } // // public static Close portal(String name) { // return new Close(name, Kind.PORTAL); // } // // public static Close statement(String name) { // return new Close(name, Kind.STATEMENT); // } // }
import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Close; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Close (F) * Byte1('C') * Identifies the message as a Close command. * * Int32 * Length of message contents in bytes, including self. * * Byte1 * 'S' to close a prepared statement; or 'P' to close a portal. * * String * The name of the prepared statement or portal to close (an empty string selects the unnamed prepared statement or portal). * * </pre> * * @author Marat Gainullin */ public class CloseEncoder extends ExtendedQueryEncoder<Close> { @Override public Class<Close> getMessageType() { return Close.class; } @Override protected byte getMessageId() { return (byte) 'C'; } @Override public void writeBody(Close msg, ByteBuffer buffer, Charset encoding) { buffer.put(msg.getKind().getCode());
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Close.java // public class Close implements ExtendedQueryMessage { // // public enum Kind { // STATEMENT((byte) 'S'), // PORTAL((byte) 'P'); // // byte code; // // Kind(byte code) { // this.code = code; // } // // public byte getCode() { // return code; // } // } // // private final Kind kind; // private final String name; // // private Close(String name, Kind kind) { // this.name = name; // this.kind = kind; // } // // public String getName() { // return name; // } // // public Kind getKind() { // return kind; // } // // public static Close portal(String name) { // return new Close(name, Kind.PORTAL); // } // // public static Close statement(String name) { // return new Close(name, Kind.STATEMENT); // } // } // Path: src/main/java/com/github/pgasync/io/frontend/CloseEncoder.java import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Close; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Close (F) * Byte1('C') * Identifies the message as a Close command. * * Int32 * Length of message contents in bytes, including self. * * Byte1 * 'S' to close a prepared statement; or 'P' to close a portal. * * String * The name of the prepared statement or portal to close (an empty string selects the unnamed prepared statement or portal). * * </pre> * * @author Marat Gainullin */ public class CloseEncoder extends ExtendedQueryEncoder<Close> { @Override public Class<Close> getMessageType() { return Close.class; } @Override protected byte getMessageId() { return (byte) 'C'; } @Override public void writeBody(Close msg, ByteBuffer buffer, Charset encoding) { buffer.put(msg.getKind().getCode());
IO.putCString(buffer, msg.getName(), encoding);