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
ihaolin/wechat
src/main/java/me/hao0/wechat/core/QrCodes.java
// Path: src/main/java/me/hao0/wechat/exception/WechatException.java // public class WechatException extends RuntimeException { // // /** // * 微信返回的errcode // */ // private Integer code; // // public WechatException(Map<String, ?> errMap) { // super("[" + errMap.get("errcode") + "]" + errMap.get("errmsg")); // code = (Integer)errMap.get("errcode"); // } // // public WechatException() { // super(); // } // // public WechatException(String message) { // super(message); // } // // public WechatException(String message, Throwable cause) { // super(message, cause); // } // // public WechatException(Throwable cause) { // super(cause); // } // // protected WechatException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public Integer getCode() { // return code; // } // } // // Path: src/main/java/me/hao0/wechat/model/qrcode/Qrcode.java // public class Qrcode implements Serializable { // // private static final long serialVersionUID = -8864173402832984445L; // // /** // * 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 // */ // private String ticket; // // /** // * 有效时间(秒) // */ // @JsonProperty("expire_seconds") // private String expireSeconds; // // /** // * 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 // */ // private String url; // // public String getTicket() { // return ticket; // } // // public void setTicket(String ticket) { // this.ticket = ticket; // } // // public String getExpireSeconds() { // return expireSeconds; // } // // public void setExpireSeconds(String expireSeconds) { // this.expireSeconds = expireSeconds; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "Qrcode{" + // "ticket='" + ticket + '\'' + // ", expireSeconds='" + expireSeconds + '\'' + // ", url='" + url + '\'' + // '}'; // } // } // // Path: src/main/java/me/hao0/wechat/model/qrcode/QrcodeType.java // public enum QrcodeType { // // /** // * 临时二维码,有过期时间,最长7天,604800s // */ // QR_SCENE("QR_SCENE"), // // /** // * 永久二维码,最多100000个 // */ // QR_LIMIT_SCENE("QR_LIMIT_SCENE"), // // /** // * 永久二维码,字符串类型,长度限制为1到64 // */ // QR_LIMIT_STR_SCENE("QR_LIMIT_STR_SCENE"); // // private String value; // // private QrcodeType(String value){ // this.value = value; // } // // public String value(){ // return value; // } // }
import com.google.common.collect.Maps; import me.hao0.wechat.exception.WechatException; import me.hao0.wechat.model.qrcode.Qrcode; import me.hao0.wechat.model.qrcode.QrcodeType; import me.hao0.common.json.Jsons; import me.hao0.common.util.Strings; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import static me.hao0.common.util.Preconditions.*;
* @param type 二维码类型,QR_SCENE为临时,QR_LIMIT_SCENE为永久,QR_LIMIT_STR_SCENE为永久的字符串参数值 * @return 二维码参数 */ private Map<String, Object> buildQrcodeParams(String sceneId, String sceneStr, QrcodeType type) { Map<String, Object> params = Maps.newHashMapWithExpectedSize(2); params.put("action_name", type.value()); Map<String, Object> sceneMap = Maps.newHashMapWithExpectedSize(1); if (!Strings.isNullOrEmpty(sceneId)) { sceneMap.put("scene_id", sceneId); }else if (!Strings.isNullOrEmpty(sceneStr)) { sceneMap.put("scene_str", sceneStr); } Map<String, Object> scene = Maps.newHashMapWithExpectedSize(1); scene.put("scene", sceneMap); params.put("action_info", scene); return params; } /** * 获取二维码链接 * @param ticket 二维码的ticket * @return 二维码链接,或抛WechatException */ private String showQrcode(String ticket){ try { return SHOW_QRCODE + URLEncoder.encode(ticket, "UTF-8"); } catch (UnsupportedEncodingException e) {
// Path: src/main/java/me/hao0/wechat/exception/WechatException.java // public class WechatException extends RuntimeException { // // /** // * 微信返回的errcode // */ // private Integer code; // // public WechatException(Map<String, ?> errMap) { // super("[" + errMap.get("errcode") + "]" + errMap.get("errmsg")); // code = (Integer)errMap.get("errcode"); // } // // public WechatException() { // super(); // } // // public WechatException(String message) { // super(message); // } // // public WechatException(String message, Throwable cause) { // super(message, cause); // } // // public WechatException(Throwable cause) { // super(cause); // } // // protected WechatException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public Integer getCode() { // return code; // } // } // // Path: src/main/java/me/hao0/wechat/model/qrcode/Qrcode.java // public class Qrcode implements Serializable { // // private static final long serialVersionUID = -8864173402832984445L; // // /** // * 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 // */ // private String ticket; // // /** // * 有效时间(秒) // */ // @JsonProperty("expire_seconds") // private String expireSeconds; // // /** // * 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 // */ // private String url; // // public String getTicket() { // return ticket; // } // // public void setTicket(String ticket) { // this.ticket = ticket; // } // // public String getExpireSeconds() { // return expireSeconds; // } // // public void setExpireSeconds(String expireSeconds) { // this.expireSeconds = expireSeconds; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "Qrcode{" + // "ticket='" + ticket + '\'' + // ", expireSeconds='" + expireSeconds + '\'' + // ", url='" + url + '\'' + // '}'; // } // } // // Path: src/main/java/me/hao0/wechat/model/qrcode/QrcodeType.java // public enum QrcodeType { // // /** // * 临时二维码,有过期时间,最长7天,604800s // */ // QR_SCENE("QR_SCENE"), // // /** // * 永久二维码,最多100000个 // */ // QR_LIMIT_SCENE("QR_LIMIT_SCENE"), // // /** // * 永久二维码,字符串类型,长度限制为1到64 // */ // QR_LIMIT_STR_SCENE("QR_LIMIT_STR_SCENE"); // // private String value; // // private QrcodeType(String value){ // this.value = value; // } // // public String value(){ // return value; // } // } // Path: src/main/java/me/hao0/wechat/core/QrCodes.java import com.google.common.collect.Maps; import me.hao0.wechat.exception.WechatException; import me.hao0.wechat.model.qrcode.Qrcode; import me.hao0.wechat.model.qrcode.QrcodeType; import me.hao0.common.json.Jsons; import me.hao0.common.util.Strings; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import static me.hao0.common.util.Preconditions.*; * @param type 二维码类型,QR_SCENE为临时,QR_LIMIT_SCENE为永久,QR_LIMIT_STR_SCENE为永久的字符串参数值 * @return 二维码参数 */ private Map<String, Object> buildQrcodeParams(String sceneId, String sceneStr, QrcodeType type) { Map<String, Object> params = Maps.newHashMapWithExpectedSize(2); params.put("action_name", type.value()); Map<String, Object> sceneMap = Maps.newHashMapWithExpectedSize(1); if (!Strings.isNullOrEmpty(sceneId)) { sceneMap.put("scene_id", sceneId); }else if (!Strings.isNullOrEmpty(sceneStr)) { sceneMap.put("scene_str", sceneStr); } Map<String, Object> scene = Maps.newHashMapWithExpectedSize(1); scene.put("scene", sceneMap); params.put("action_info", scene); return params; } /** * 获取二维码链接 * @param ticket 二维码的ticket * @return 二维码链接,或抛WechatException */ private String showQrcode(String ticket){ try { return SHOW_QRCODE + URLEncoder.encode(ticket, "UTF-8"); } catch (UnsupportedEncodingException e) {
throw new WechatException(e);
KAlO2/PerfectShow
app/src/main/java/com/wonderful/ishow/widget/AspectRatioTextView.java
// Path: app/src/main/java/com/wonderful/ishow/bean/AspectRatio.java // public class AspectRatio implements Parcelable { // /** // * Use source image aspect ratio as default. // */ // public static final int DEFAULT_ASPECT_RATIO = 0; // // @Nullable // private String mAspectRatioTitle; // private int mAspectRatioX; // private int mAspectRatioY; // // public AspectRatio(@Nullable String aspectRatioTitle, int aspectRatioX, int aspectRatioY) { // mAspectRatioTitle = aspectRatioTitle; // mAspectRatioX = aspectRatioX; // mAspectRatioY = aspectRatioY; // } // // protected AspectRatio(Parcel in) { // mAspectRatioTitle = in.readString(); // mAspectRatioX = in.readInt(); // mAspectRatioY = in.readInt(); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mAspectRatioTitle); // dest.writeInt(mAspectRatioX); // dest.writeInt(mAspectRatioY); // } // // @Override // public int describeContents() { // return 0; // } // // public static final Creator<AspectRatio> CREATOR = new Creator<AspectRatio>() { // @Override // public AspectRatio createFromParcel(Parcel in) { // return new AspectRatio(in); // } // // @Override // public AspectRatio[] newArray(int size) { // return new AspectRatio[size]; // } // }; // // public void setmAspectRatioTitle(String title) { // mAspectRatioTitle = title; // } // // @Nullable // public String getAspectRatioTitle() { // return mAspectRatioTitle; // } // // public int getAspectRatioX() { // return mAspectRatioX; // } // // public int getAspectRatioY() { // return mAspectRatioY; // } // // public float getAspectRatio() { // if(mAspectRatioX == DEFAULT_ASPECT_RATIO || mAspectRatioY == DEFAULT_ASPECT_RATIO) // return DEFAULT_ASPECT_RATIO; // else // return mAspectRatioX / mAspectRatioY; // } // // public synchronized void switchOrientation() { // if(mAspectRatioX == DEFAULT_ASPECT_RATIO || mAspectRatioY == DEFAULT_ASPECT_RATIO) // return; // // int tmp = mAspectRatioX; // mAspectRatioX = mAspectRatioY; // mAspectRatioY = tmp; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.os.Build; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.Gravity; import android.widget.TextView; import com.wonderful.ishow.R; import com.wonderful.ishow.bean.AspectRatio;
package com.wonderful.ishow.widget; public class AspectRatioTextView extends TextView { private final Rect mBounds = new Rect(); private final Paint mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private float mDotSize;
// Path: app/src/main/java/com/wonderful/ishow/bean/AspectRatio.java // public class AspectRatio implements Parcelable { // /** // * Use source image aspect ratio as default. // */ // public static final int DEFAULT_ASPECT_RATIO = 0; // // @Nullable // private String mAspectRatioTitle; // private int mAspectRatioX; // private int mAspectRatioY; // // public AspectRatio(@Nullable String aspectRatioTitle, int aspectRatioX, int aspectRatioY) { // mAspectRatioTitle = aspectRatioTitle; // mAspectRatioX = aspectRatioX; // mAspectRatioY = aspectRatioY; // } // // protected AspectRatio(Parcel in) { // mAspectRatioTitle = in.readString(); // mAspectRatioX = in.readInt(); // mAspectRatioY = in.readInt(); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mAspectRatioTitle); // dest.writeInt(mAspectRatioX); // dest.writeInt(mAspectRatioY); // } // // @Override // public int describeContents() { // return 0; // } // // public static final Creator<AspectRatio> CREATOR = new Creator<AspectRatio>() { // @Override // public AspectRatio createFromParcel(Parcel in) { // return new AspectRatio(in); // } // // @Override // public AspectRatio[] newArray(int size) { // return new AspectRatio[size]; // } // }; // // public void setmAspectRatioTitle(String title) { // mAspectRatioTitle = title; // } // // @Nullable // public String getAspectRatioTitle() { // return mAspectRatioTitle; // } // // public int getAspectRatioX() { // return mAspectRatioX; // } // // public int getAspectRatioY() { // return mAspectRatioY; // } // // public float getAspectRatio() { // if(mAspectRatioX == DEFAULT_ASPECT_RATIO || mAspectRatioY == DEFAULT_ASPECT_RATIO) // return DEFAULT_ASPECT_RATIO; // else // return mAspectRatioX / mAspectRatioY; // } // // public synchronized void switchOrientation() { // if(mAspectRatioX == DEFAULT_ASPECT_RATIO || mAspectRatioY == DEFAULT_ASPECT_RATIO) // return; // // int tmp = mAspectRatioX; // mAspectRatioX = mAspectRatioY; // mAspectRatioY = tmp; // } // } // Path: app/src/main/java/com/wonderful/ishow/widget/AspectRatioTextView.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.os.Build; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.Gravity; import android.widget.TextView; import com.wonderful.ishow.R; import com.wonderful.ishow.bean.AspectRatio; package com.wonderful.ishow.widget; public class AspectRatioTextView extends TextView { private final Rect mBounds = new Rect(); private final Paint mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private float mDotSize;
private AspectRatio mAspectRatio;
KAlO2/PerfectShow
app/src/main/java/com/wonderful/ishow/util/BitmapLoadTask.java
// Path: app/src/main/java/com/wonderful/ishow/bean/ExifInfo.java // public class ExifInfo { // // private int mExifOrientation; // private int mExifDegrees; // private int mExifTranslation; // // public ExifInfo(int exifOrientation, int exifDegrees, int exifTranslation) { // mExifOrientation = exifOrientation; // mExifDegrees = exifDegrees; // mExifTranslation = exifTranslation; // } // // public int getExifOrientation() { // return mExifOrientation; // } // // public int getExifDegrees() { // return mExifDegrees; // } // // public int getExifTranslation() { // return mExifTranslation; // } // // public void setExifOrientation(int exifOrientation) { // mExifOrientation = exifOrientation; // } // // public void setExifDegrees(int exifDegrees) { // mExifDegrees = exifDegrees; // } // // public void setExifTranslation(int exifTranslation) { // mExifTranslation = exifTranslation; // } // // @Override // public boolean equals(Object o) { // if(this == o) // return true; // if(o == null || getClass() != o.getClass()) // return false; // // ExifInfo exifInfo = (ExifInfo) o; // // if(mExifOrientation != exifInfo.mExifOrientation) // return false; // if(mExifDegrees != exifInfo.mExifDegrees) // return false; // return mExifTranslation == exifInfo.mExifTranslation; // // } // // @Override // public int hashCode() { // int result = mExifOrientation; // result = 31 * result + mExifDegrees; // result = 31 * result + mExifTranslation; // return result; // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.wonderful.ishow.bean.ExifInfo;
package com.wonderful.ishow.util; /** * Creates and returns a Bitmap for a given Uri(String url). inSampleSize is calculated based on * requiredWidth property. However can be adjusted if OOM occurs. If any EXIF config is found - * bitmap is transformed properly. */ public class BitmapLoadTask extends AsyncTask<Void, Void, BitmapLoadTask.BitmapWorkerResult> { private static final String TAG = BitmapLoadTask.class.getSimpleName(); public interface BitmapLoadCallback {
// Path: app/src/main/java/com/wonderful/ishow/bean/ExifInfo.java // public class ExifInfo { // // private int mExifOrientation; // private int mExifDegrees; // private int mExifTranslation; // // public ExifInfo(int exifOrientation, int exifDegrees, int exifTranslation) { // mExifOrientation = exifOrientation; // mExifDegrees = exifDegrees; // mExifTranslation = exifTranslation; // } // // public int getExifOrientation() { // return mExifOrientation; // } // // public int getExifDegrees() { // return mExifDegrees; // } // // public int getExifTranslation() { // return mExifTranslation; // } // // public void setExifOrientation(int exifOrientation) { // mExifOrientation = exifOrientation; // } // // public void setExifDegrees(int exifDegrees) { // mExifDegrees = exifDegrees; // } // // public void setExifTranslation(int exifTranslation) { // mExifTranslation = exifTranslation; // } // // @Override // public boolean equals(Object o) { // if(this == o) // return true; // if(o == null || getClass() != o.getClass()) // return false; // // ExifInfo exifInfo = (ExifInfo) o; // // if(mExifOrientation != exifInfo.mExifOrientation) // return false; // if(mExifDegrees != exifInfo.mExifDegrees) // return false; // return mExifTranslation == exifInfo.mExifTranslation; // // } // // @Override // public int hashCode() { // int result = mExifOrientation; // result = 31 * result + mExifDegrees; // result = 31 * result + mExifTranslation; // return result; // } // // } // Path: app/src/main/java/com/wonderful/ishow/util/BitmapLoadTask.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.wonderful.ishow.bean.ExifInfo; package com.wonderful.ishow.util; /** * Creates and returns a Bitmap for a given Uri(String url). inSampleSize is calculated based on * requiredWidth property. However can be adjusted if OOM occurs. If any EXIF config is found - * bitmap is transformed properly. */ public class BitmapLoadTask extends AsyncTask<Void, Void, BitmapLoadTask.BitmapWorkerResult> { private static final String TAG = BitmapLoadTask.class.getSimpleName(); public interface BitmapLoadCallback {
void onBitmapLoaded(@NonNull Bitmap bitmap, @NonNull ExifInfo exifInfo, @NonNull String imageInputPath,
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // }
import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.cloudera.director.google.util.Urls; import java.util.List;
List<String> pathParts = Lists.newArrayList("zones", zone); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { List<String> pathParts = Lists.newArrayList("regions", region); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } public static String buildGlobalUrl(String projectId, String... resourcePathParts) { List<String> pathParts = Lists.newArrayList("global"); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) {
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // } // Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.cloudera.director.google.util.Urls; import java.util.List; List<String> pathParts = Lists.newArrayList("zones", zone); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { List<String> pathParts = Lists.newArrayList("regions", region); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } public static String buildGlobalUrl(String projectId, String... resourcePathParts) { List<String> pathParts = Lists.newArrayList("global"); if (resourcePathParts != null) { pathParts.addAll(Lists.newArrayList(resourcePathParts)); } return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); } static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) {
return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts);
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // }
import com.cloudera.director.google.util.Urls;
/* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.sql.util; public class SQLUrls { public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) {
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // } // Path: provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java import com.cloudera.director.google.util.Urls; /* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.sql.util; public class SQLUrls { public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) {
return Urls.buildGenericApisUrl("sql", "v1beta4", projectId, resourcePathParts);
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/sql/GoogleCloudSQLProviderConfigurationValidator.java
// Path: provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java // public class GoogleCredentials { // // private final Config applicationProperties; // private final String projectId; // private final String jsonKey; // private final Compute compute; // private final SQLAdmin sqlAdmin; // // public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { // this.applicationProperties = applicationProperties; // this.projectId = projectId; // this.jsonKey = jsonKey; // this.compute = buildCompute(); // this.sqlAdmin = buildSQLAdmin(); // } // // private Compute buildCompute() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); // } else { // Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(COMPUTE_SCOPES); // } // // return new Compute.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private SQLAdmin buildSQLAdmin() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)); // } else { // Collection SQLSERVICE_ADMIN_SCOPES = Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(SQLSERVICE_ADMIN_SCOPES); // } // // return new SQLAdmin.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public String getProjectId() { // return projectId; // } // // public String getJsonKey() { // return jsonKey; // } // // public Compute getCompute() { // return compute; // } // // public SQLAdmin getSQLAdmin() { // return sqlAdmin; // } // // public boolean match(String projectId, String jsonKey) { // return projectId.equals(this.projectId) && // jsonKey.equals(this.jsonKey); // } // }
import java.io.IOException; import java.util.List; import static com.cloudera.director.google.sql.GoogleCloudSQLProviderConfigurationProperty.REGION; import static com.cloudera.director.spi.v1.model.util.Validations.addError; import com.cloudera.director.google.internal.GoogleCredentials; import com.cloudera.director.spi.v1.model.ConfigurationValidator; import com.cloudera.director.spi.v1.model.Configured; import com.cloudera.director.spi.v1.model.LocalizationContext; import com.cloudera.director.spi.v1.model.exception.PluginExceptionConditionAccumulator; import com.cloudera.director.spi.v1.model.exception.TransientProviderException; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.model.Tier; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.sql; /** * Validates Google Cloud SQL provider configuration. */ public class GoogleCloudSQLProviderConfigurationValidator implements ConfigurationValidator { private static final Logger LOG = LoggerFactory.getLogger(GoogleCloudSQLProviderConfigurationValidator.class); @VisibleForTesting static final String REGION_NOT_FOUND_MSG = "Region '%s' not found for project '%s'.";
// Path: provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java // public class GoogleCredentials { // // private final Config applicationProperties; // private final String projectId; // private final String jsonKey; // private final Compute compute; // private final SQLAdmin sqlAdmin; // // public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { // this.applicationProperties = applicationProperties; // this.projectId = projectId; // this.jsonKey = jsonKey; // this.compute = buildCompute(); // this.sqlAdmin = buildSQLAdmin(); // } // // private Compute buildCompute() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); // } else { // Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(COMPUTE_SCOPES); // } // // return new Compute.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private SQLAdmin buildSQLAdmin() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)); // } else { // Collection SQLSERVICE_ADMIN_SCOPES = Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(SQLSERVICE_ADMIN_SCOPES); // } // // return new SQLAdmin.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public String getProjectId() { // return projectId; // } // // public String getJsonKey() { // return jsonKey; // } // // public Compute getCompute() { // return compute; // } // // public SQLAdmin getSQLAdmin() { // return sqlAdmin; // } // // public boolean match(String projectId, String jsonKey) { // return projectId.equals(this.projectId) && // jsonKey.equals(this.jsonKey); // } // } // Path: provider/src/main/java/com/cloudera/director/google/sql/GoogleCloudSQLProviderConfigurationValidator.java import java.io.IOException; import java.util.List; import static com.cloudera.director.google.sql.GoogleCloudSQLProviderConfigurationProperty.REGION; import static com.cloudera.director.spi.v1.model.util.Validations.addError; import com.cloudera.director.google.internal.GoogleCredentials; import com.cloudera.director.spi.v1.model.ConfigurationValidator; import com.cloudera.director.spi.v1.model.Configured; import com.cloudera.director.spi.v1.model.LocalizationContext; import com.cloudera.director.spi.v1.model.exception.PluginExceptionConditionAccumulator; import com.cloudera.director.spi.v1.model.exception.TransientProviderException; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.model.Tier; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.sql; /** * Validates Google Cloud SQL provider configuration. */ public class GoogleCloudSQLProviderConfigurationValidator implements ConfigurationValidator { private static final Logger LOG = LoggerFactory.getLogger(GoogleCloudSQLProviderConfigurationValidator.class); @VisibleForTesting static final String REGION_NOT_FOUND_MSG = "Region '%s' not found for project '%s'.";
private GoogleCredentials credentials;
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/GoogleLauncher.java
// Path: provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java // public class GoogleCredentials { // // private final Config applicationProperties; // private final String projectId; // private final String jsonKey; // private final Compute compute; // private final SQLAdmin sqlAdmin; // // public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { // this.applicationProperties = applicationProperties; // this.projectId = projectId; // this.jsonKey = jsonKey; // this.compute = buildCompute(); // this.sqlAdmin = buildSQLAdmin(); // } // // private Compute buildCompute() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); // } else { // Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(COMPUTE_SCOPES); // } // // return new Compute.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private SQLAdmin buildSQLAdmin() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)); // } else { // Collection SQLSERVICE_ADMIN_SCOPES = Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(SQLSERVICE_ADMIN_SCOPES); // } // // return new SQLAdmin.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public String getProjectId() { // return projectId; // } // // public String getJsonKey() { // return jsonKey; // } // // public Compute getCompute() { // return compute; // } // // public SQLAdmin getSQLAdmin() { // return sqlAdmin; // } // // public boolean match(String projectId, String jsonKey) { // return projectId.equals(this.projectId) && // jsonKey.equals(this.jsonKey); // } // }
import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Locale; import com.cloudera.director.google.internal.GoogleCredentials; import com.cloudera.director.spi.v1.common.http.HttpProxyParameters; import com.cloudera.director.spi.v1.model.Configured; import com.cloudera.director.spi.v1.model.LocalizationContext; import com.cloudera.director.spi.v1.model.exception.InvalidCredentialsException; import com.cloudera.director.spi.v1.provider.CloudProvider; import com.cloudera.director.spi.v1.provider.CredentialsProvider; import com.cloudera.director.spi.v1.provider.util.AbstractLauncher; import com.google.api.services.compute.Compute; import com.google.common.annotations.VisibleForTesting; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigParseOptions; import com.typesafe.config.ConfigSyntax;
return ConfigFactory.parseResourcesAnySyntax(GoogleLauncher.class, configPath, options); } /** * Parses the specified configuration file. * * @param configFile the configuration file * @return the parsed configuration */ private static Config parseConfigFromFile(File configFile) { ConfigParseOptions options = ConfigParseOptions.defaults() .setSyntax(ConfigSyntax.CONF) .setAllowMissing(false); return ConfigFactory.parseFileAnySyntax(configFile, options); } @Override public CloudProvider createCloudProvider(String cloudProviderId, Configured configuration, Locale locale) { if (!GoogleCloudProvider.ID.equals(cloudProviderId)) { throw new IllegalArgumentException("Cloud provider not found: " + cloudProviderId); } LocalizationContext localizationContext = getLocalizationContext(locale); // At this point the configuration object will already contain // the required data for authentication.
// Path: provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java // public class GoogleCredentials { // // private final Config applicationProperties; // private final String projectId; // private final String jsonKey; // private final Compute compute; // private final SQLAdmin sqlAdmin; // // public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { // this.applicationProperties = applicationProperties; // this.projectId = projectId; // this.jsonKey = jsonKey; // this.compute = buildCompute(); // this.sqlAdmin = buildSQLAdmin(); // } // // private Compute buildCompute() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); // } else { // Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(COMPUTE_SCOPES); // } // // return new Compute.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private SQLAdmin buildSQLAdmin() { // try { // JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // GoogleCredential credential; // // if (jsonKey != null) { // credential = GoogleCredential.fromStream( // new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) // .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)); // } else { // Collection SQLSERVICE_ADMIN_SCOPES = Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN); // // credential = GoogleCredential // .getApplicationDefault(httpTransport, JSON_FACTORY) // .createScoped(SQLSERVICE_ADMIN_SCOPES); // } // // return new SQLAdmin.Builder(httpTransport, // JSON_FACTORY, // null) // .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) // .setHttpRequestInitializer(credential) // .build(); // // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public String getProjectId() { // return projectId; // } // // public String getJsonKey() { // return jsonKey; // } // // public Compute getCompute() { // return compute; // } // // public SQLAdmin getSQLAdmin() { // return sqlAdmin; // } // // public boolean match(String projectId, String jsonKey) { // return projectId.equals(this.projectId) && // jsonKey.equals(this.jsonKey); // } // } // Path: provider/src/main/java/com/cloudera/director/google/GoogleLauncher.java import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Locale; import com.cloudera.director.google.internal.GoogleCredentials; import com.cloudera.director.spi.v1.common.http.HttpProxyParameters; import com.cloudera.director.spi.v1.model.Configured; import com.cloudera.director.spi.v1.model.LocalizationContext; import com.cloudera.director.spi.v1.model.exception.InvalidCredentialsException; import com.cloudera.director.spi.v1.provider.CloudProvider; import com.cloudera.director.spi.v1.provider.CredentialsProvider; import com.cloudera.director.spi.v1.provider.util.AbstractLauncher; import com.google.api.services.compute.Compute; import com.google.common.annotations.VisibleForTesting; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigParseOptions; import com.typesafe.config.ConfigSyntax; return ConfigFactory.parseResourcesAnySyntax(GoogleLauncher.class, configPath, options); } /** * Parses the specified configuration file. * * @param configFile the configuration file * @return the parsed configuration */ private static Config parseConfigFromFile(File configFile) { ConfigParseOptions options = ConfigParseOptions.defaults() .setSyntax(ConfigSyntax.CONF) .setAllowMissing(false); return ConfigFactory.parseFileAnySyntax(configFile, options); } @Override public CloudProvider createCloudProvider(String cloudProviderId, Configured configuration, Locale locale) { if (!GoogleCloudProvider.ID.equals(cloudProviderId)) { throw new IllegalArgumentException("Cloud provider not found: " + cloudProviderId); } LocalizationContext localizationContext = getLocalizationContext(locale); // At this point the configuration object will already contain // the required data for authentication.
CredentialsProvider<GoogleCredentials> provider = new GoogleCredentialsProvider(applicationProperties);
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/compute/GoogleComputeInstance.java
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // }
import com.cloudera.director.google.util.Dates; import com.cloudera.director.google.util.Urls; import com.cloudera.director.spi.v1.compute.util.AbstractComputeInstance; import com.cloudera.director.spi.v1.model.DisplayProperty; import com.cloudera.director.spi.v1.model.DisplayPropertyToken; import com.cloudera.director.spi.v1.model.util.SimpleDisplayPropertyBuilder; import com.cloudera.director.spi.v1.util.DisplayPropertiesUtil; import com.google.api.services.compute.model.AccessConfig; import com.google.api.services.compute.model.Disk; import com.google.api.services.compute.model.Instance; import com.google.api.services.compute.model.NetworkInterface; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import java.util.Map;
/* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.compute; /** * Google Compute instance. */ public class GoogleComputeInstance extends AbstractComputeInstance<GoogleComputeInstanceTemplate, Instance> { private static final Logger LOG = LoggerFactory.getLogger(GoogleComputeInstance.class); /** * The list of display properties (including inherited properties). */ private static final List<DisplayProperty> DISPLAY_PROPERTIES = DisplayPropertiesUtil.asDisplayPropertyList(GoogleComputeInstanceDisplayPropertyToken.values()); /** * Returns the list of display properties for a Google instance, including inherited properties. * * @return the list of display properties for a Google instance, including inherited properties */ public static List<DisplayProperty> getDisplayProperties() { return DISPLAY_PROPERTIES; } /** * Google compute instance display properties. */ public enum GoogleComputeInstanceDisplayPropertyToken implements DisplayPropertyToken { IMAGE_ID(new SimpleDisplayPropertyBuilder() .displayKey("imageId") .name("Image ID") .defaultDescription("The ID of the image used to launch the instance.") .sensitive(false) .build()) { @Override protected String getPropertyValue(Instance instance, Disk bootDisk) {
// Path: provider/src/main/java/com/cloudera/director/google/util/Urls.java // public final class Urls { // // @VisibleForTesting // static final String MALFORMED_RESOURCE_URL_MSG = "Malformed resource url '%s'."; // // private Urls() {} // // public static String getLocalName(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // GenericUrl url = new GenericUrl(fullResourceUrl); // return Iterables.getLast(url.getPathParts()); // } // // public static String getProject(String fullResourceUrl) { // if (fullResourceUrl == null || fullResourceUrl.isEmpty()) { // return null; // } // // List<String> pathParts = new GenericUrl(fullResourceUrl).getPathParts(); // // if (pathParts == null) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } // // String[] urlParts = Iterables.toArray(pathParts, String.class); // // // Resource urls look like so: https://www.googleapis.com/compute/v1/projects/rhel-cloud/global/images/rhel-6-v20150526 // // The path parts begin after the host and include a leading "" path part to force the leading slash. // if (urlParts.length < 8) { // throw new IllegalArgumentException(String.format(MALFORMED_RESOURCE_URL_MSG, fullResourceUrl)); // } else { // return urlParts[urlParts.length - 4]; // } // } // // public static String buildGenericApisUrl(String domainName, String version, String projectId, String... resourcePathParts) { // GenericUrl genericUrl = new GenericUrl(); // genericUrl.setScheme("https"); // genericUrl.setHost("www.googleapis.com"); // // List<String> pathParts = Lists.newArrayList("", domainName, version); // pathParts.add("projects"); // pathParts.add(projectId); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // genericUrl.setPathParts(pathParts); // // return genericUrl.build(); // } // } // Path: provider/src/main/java/com/cloudera/director/google/compute/GoogleComputeInstance.java import com.cloudera.director.google.util.Dates; import com.cloudera.director.google.util.Urls; import com.cloudera.director.spi.v1.compute.util.AbstractComputeInstance; import com.cloudera.director.spi.v1.model.DisplayProperty; import com.cloudera.director.spi.v1.model.DisplayPropertyToken; import com.cloudera.director.spi.v1.model.util.SimpleDisplayPropertyBuilder; import com.cloudera.director.spi.v1.util.DisplayPropertiesUtil; import com.google.api.services.compute.model.AccessConfig; import com.google.api.services.compute.model.Disk; import com.google.api.services.compute.model.Instance; import com.google.api.services.compute.model.NetworkInterface; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import java.util.Map; /* * Copyright (c) 2015 Google, Inc. * * 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.cloudera.director.google.compute; /** * Google Compute instance. */ public class GoogleComputeInstance extends AbstractComputeInstance<GoogleComputeInstanceTemplate, Instance> { private static final Logger LOG = LoggerFactory.getLogger(GoogleComputeInstance.class); /** * The list of display properties (including inherited properties). */ private static final List<DisplayProperty> DISPLAY_PROPERTIES = DisplayPropertiesUtil.asDisplayPropertyList(GoogleComputeInstanceDisplayPropertyToken.values()); /** * Returns the list of display properties for a Google instance, including inherited properties. * * @return the list of display properties for a Google instance, including inherited properties */ public static List<DisplayProperty> getDisplayProperties() { return DISPLAY_PROPERTIES; } /** * Google compute instance display properties. */ public enum GoogleComputeInstanceDisplayPropertyToken implements DisplayPropertyToken { IMAGE_ID(new SimpleDisplayPropertyBuilder() .displayKey("imageId") .name("Image ID") .defaultDescription("The ID of the image used to launch the instance.") .sensitive(false) .build()) { @Override protected String getPropertyValue(Instance instance, Disk bootDisk) {
return Urls.getLocalName(bootDisk.getSourceImage());
cloudera/director-google-plugin
provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java
// Path: provider/src/main/java/com/cloudera/director/google/util/Names.java // public class Names { // // public static String buildApplicationNameVersionTag(Config applicationProperties) { // return applicationProperties.getString("application.name") + "/" + // applicationProperties.getString("application.version"); // } // // public static String convertCloudSQLRegionToComputeRegion(String cloudSQLRegion, Config googleConfig) { // return googleConfig.getString(Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + cloudSQLRegion); // } // }
import java.util.Collections; import com.cloudera.director.google.util.Names; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.compute.Compute; import com.google.api.services.compute.ComputeScopes; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.SQLAdminScopes; import com.typesafe.config.Config; import java.io.ByteArrayInputStream; import java.util.Collection;
public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { this.applicationProperties = applicationProperties; this.projectId = projectId; this.jsonKey = jsonKey; this.compute = buildCompute(); this.sqlAdmin = buildSQLAdmin(); } private Compute buildCompute() { try { JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; if (jsonKey != null) { credential = GoogleCredential.fromStream( new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); } else { Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); credential = GoogleCredential .getApplicationDefault(httpTransport, JSON_FACTORY) .createScoped(COMPUTE_SCOPES); } return new Compute.Builder(httpTransport, JSON_FACTORY, null)
// Path: provider/src/main/java/com/cloudera/director/google/util/Names.java // public class Names { // // public static String buildApplicationNameVersionTag(Config applicationProperties) { // return applicationProperties.getString("application.name") + "/" + // applicationProperties.getString("application.version"); // } // // public static String convertCloudSQLRegionToComputeRegion(String cloudSQLRegion, Config googleConfig) { // return googleConfig.getString(Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + cloudSQLRegion); // } // } // Path: provider/src/main/java/com/cloudera/director/google/internal/GoogleCredentials.java import java.util.Collections; import com.cloudera.director.google.util.Names; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.compute.Compute; import com.google.api.services.compute.ComputeScopes; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.SQLAdminScopes; import com.typesafe.config.Config; import java.io.ByteArrayInputStream; import java.util.Collection; public GoogleCredentials(Config applicationProperties, String projectId, String jsonKey) { this.applicationProperties = applicationProperties; this.projectId = projectId; this.jsonKey = jsonKey; this.compute = buildCompute(); this.sqlAdmin = buildSQLAdmin(); } private Compute buildCompute() { try { JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; if (jsonKey != null) { credential = GoogleCredential.fromStream( new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); } else { Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); credential = GoogleCredential .getApplicationDefault(httpTransport, JSON_FACTORY) .createScoped(COMPUTE_SCOPES); } return new Compute.Builder(httpTransport, JSON_FACTORY, null)
.setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties))
cloudera/director-google-plugin
tests/src/test/java/com/cloudera/director/google/util/UrlsTest.java
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // }
import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; import com.cloudera.director.google.compute.util.ComputeUrls; import org.junit.Test; import java.net.MalformedURLException;
Urls.getProject(someUrl); fail("An exception should have been thrown when we attempted to parse a malformed url."); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(String.format(Urls.MALFORMED_RESOURCE_URL_MSG, someUrl)); } someUrl = "https://www.googleapis.com/compute/v1/projects/rhel-cloud/images/rhel-6-v20150526"; try { Urls.getProject(someUrl); fail("An exception should have been thrown when we attempted to parse a malformed url."); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(String.format(Urls.MALFORMED_RESOURCE_URL_MSG, someUrl)); } } @Test public void testGetProject_Null() { assertThat(Urls.getProject(null)).isEqualTo(null); } @Test public void testGetProject_EmptyString() { assertThat(Urls.getProject("")).isEqualTo(null); } @Test public void testBuildZonalUrl() {
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // } // Path: tests/src/test/java/com/cloudera/director/google/util/UrlsTest.java import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; import com.cloudera.director.google.compute.util.ComputeUrls; import org.junit.Test; import java.net.MalformedURLException; Urls.getProject(someUrl); fail("An exception should have been thrown when we attempted to parse a malformed url."); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(String.format(Urls.MALFORMED_RESOURCE_URL_MSG, someUrl)); } someUrl = "https://www.googleapis.com/compute/v1/projects/rhel-cloud/images/rhel-6-v20150526"; try { Urls.getProject(someUrl); fail("An exception should have been thrown when we attempted to parse a malformed url."); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(String.format(Urls.MALFORMED_RESOURCE_URL_MSG, someUrl)); } } @Test public void testGetProject_Null() { assertThat(Urls.getProject(null)).isEqualTo(null); } @Test public void testGetProject_EmptyString() { assertThat(Urls.getProject("")).isEqualTo(null); } @Test public void testBuildZonalUrl() {
assertThat(ComputeUrls.buildZonalUrl("some-project", "us-central1-f")).endsWith("/some-project/zones/us-central1-f");
cloudera/director-google-plugin
tests/src/test/java/com/cloudera/director/google/TestUtils.java
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // } // // Path: provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java // public class SQLUrls { // // public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("sql", "v1beta4", projectId, resourcePathParts); // } // }
import static org.junit.Assert.fail; import com.cloudera.director.google.compute.util.ComputeUrls; import com.cloudera.director.google.shaded.com.typesafe.config.Config; import com.cloudera.director.google.shaded.com.typesafe.config.ConfigFactory; import com.cloudera.director.google.sql.util.SQLUrls; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
public static Config buildApplicationPropertiesConfig() throws IOException { Map<String, String> applicationProperties = new HashMap<String, String>(); applicationProperties.put("application.name", "Cloudera-Director-Google-Plugin"); applicationProperties.put("application.version", "1.0.0-SNAPSHOT"); return ConfigFactory.parseMap(applicationProperties); } public static Config buildGoogleConfig() throws IOException { Map<String, String> googleConfig = new HashMap<String, String>(); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "centos6", buildImageUrl("centos-cloud", "centos-6-v20150526")); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "rhel6", buildImageUrl("rhel-cloud", "rhel-6-v20150526")); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "us-central", "us-central1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "europe-west1", "europe-west1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "asia-east1", "asia-east1"); googleConfig.put(Configurations.COMPUTE_POLLING_TIMEOUT_KEY, "180"); googleConfig.put(Configurations.COMPUTE_MAX_POLLING_INTERVAL_KEY, "8"); return ConfigFactory.parseMap(googleConfig); } public static String buildImageUrl(String projectId, String image) {
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // } // // Path: provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java // public class SQLUrls { // // public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("sql", "v1beta4", projectId, resourcePathParts); // } // } // Path: tests/src/test/java/com/cloudera/director/google/TestUtils.java import static org.junit.Assert.fail; import com.cloudera.director.google.compute.util.ComputeUrls; import com.cloudera.director.google.shaded.com.typesafe.config.Config; import com.cloudera.director.google.shaded.com.typesafe.config.ConfigFactory; import com.cloudera.director.google.sql.util.SQLUrls; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public static Config buildApplicationPropertiesConfig() throws IOException { Map<String, String> applicationProperties = new HashMap<String, String>(); applicationProperties.put("application.name", "Cloudera-Director-Google-Plugin"); applicationProperties.put("application.version", "1.0.0-SNAPSHOT"); return ConfigFactory.parseMap(applicationProperties); } public static Config buildGoogleConfig() throws IOException { Map<String, String> googleConfig = new HashMap<String, String>(); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "centos6", buildImageUrl("centos-cloud", "centos-6-v20150526")); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "rhel6", buildImageUrl("rhel-cloud", "rhel-6-v20150526")); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "us-central", "us-central1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "europe-west1", "europe-west1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "asia-east1", "asia-east1"); googleConfig.put(Configurations.COMPUTE_POLLING_TIMEOUT_KEY, "180"); googleConfig.put(Configurations.COMPUTE_MAX_POLLING_INTERVAL_KEY, "8"); return ConfigFactory.parseMap(googleConfig); } public static String buildImageUrl(String projectId, String image) {
return ComputeUrls.buildGlobalUrl(projectId, "images", image);
cloudera/director-google-plugin
tests/src/test/java/com/cloudera/director/google/TestUtils.java
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // } // // Path: provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java // public class SQLUrls { // // public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("sql", "v1beta4", projectId, resourcePathParts); // } // }
import static org.junit.Assert.fail; import com.cloudera.director.google.compute.util.ComputeUrls; import com.cloudera.director.google.shaded.com.typesafe.config.Config; import com.cloudera.director.google.shaded.com.typesafe.config.ConfigFactory; import com.cloudera.director.google.sql.util.SQLUrls; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
public static Config buildGoogleConfig() throws IOException { Map<String, String> googleConfig = new HashMap<String, String>(); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "centos6", buildImageUrl("centos-cloud", "centos-6-v20150526")); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "rhel6", buildImageUrl("rhel-cloud", "rhel-6-v20150526")); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "us-central", "us-central1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "europe-west1", "europe-west1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "asia-east1", "asia-east1"); googleConfig.put(Configurations.COMPUTE_POLLING_TIMEOUT_KEY, "180"); googleConfig.put(Configurations.COMPUTE_MAX_POLLING_INTERVAL_KEY, "8"); return ConfigFactory.parseMap(googleConfig); } public static String buildImageUrl(String projectId, String image) { return ComputeUrls.buildGlobalUrl(projectId, "images", image); } public static String buildComputeInstanceUrl(String projectId, String zone, String instanceName) { return ComputeUrls.buildZonalUrl(projectId, zone, "instances", instanceName); } public static String buildDatabaseInstanceUrl(String projectId, String instanceName) {
// Path: provider/src/main/java/com/cloudera/director/google/compute/util/ComputeUrls.java // public class ComputeUrls { // // private ComputeUrls() {} // // public static String buildDiskTypeUrl(String projectId, String zone, String dataDiskType) { // String diskTypePath; // // if (dataDiskType.equals("LocalSSD")) { // diskTypePath = "local-ssd"; // } else if (dataDiskType.equals("SSD")) { // diskTypePath = "pd-ssd"; // } else { // // The value will already have been checked by the validator. // // Assume 'Standard'. // diskTypePath = "pd-standard"; // } // // return buildZonalUrl(projectId, zone, "diskTypes", diskTypePath); // } // // public static String buildDiskUrl(String projectId, String zone, String diskName) { // return buildZonalUrl(projectId, zone, "disks", diskName); // } // // public static String buildMachineTypeUrl(String projectId, String zone, String machineType) { // return buildZonalUrl(projectId, zone, "machineTypes", machineType); // } // // public static String buildNetworkUrl(String projectId, String networkName) { // return buildGlobalUrl(projectId, "networks", networkName); // } // // public static String buildSubnetUrl(String projectId, String region, String subnetName){ // return buildRegionalUrl(projectId, region, "subnetworks", subnetName); // } // // public static String buildZonalUrl(String projectId, String zone, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("zones", zone); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildRegionalUrl(String projectId, String region, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("regions", region); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // public static String buildGlobalUrl(String projectId, String... resourcePathParts) { // List<String> pathParts = Lists.newArrayList("global"); // // if (resourcePathParts != null) { // pathParts.addAll(Lists.newArrayList(resourcePathParts)); // } // // return buildGoogleComputeApisUrl(projectId, Iterables.toArray(pathParts, String.class)); // } // // static String buildGoogleComputeApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("compute", "v1", projectId, resourcePathParts); // } // } // // Path: provider/src/main/java/com/cloudera/director/google/sql/util/SQLUrls.java // public class SQLUrls { // // public static String buildGoogleCloudSQLApisUrl(String projectId, String... resourcePathParts) { // return Urls.buildGenericApisUrl("sql", "v1beta4", projectId, resourcePathParts); // } // } // Path: tests/src/test/java/com/cloudera/director/google/TestUtils.java import static org.junit.Assert.fail; import com.cloudera.director.google.compute.util.ComputeUrls; import com.cloudera.director.google.shaded.com.typesafe.config.Config; import com.cloudera.director.google.shaded.com.typesafe.config.ConfigFactory; import com.cloudera.director.google.sql.util.SQLUrls; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public static Config buildGoogleConfig() throws IOException { Map<String, String> googleConfig = new HashMap<String, String>(); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "centos6", buildImageUrl("centos-cloud", "centos-6-v20150526")); googleConfig.put( Configurations.IMAGE_ALIASES_SECTION + "rhel6", buildImageUrl("rhel-cloud", "rhel-6-v20150526")); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "us-central", "us-central1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "europe-west1", "europe-west1"); googleConfig.put( Configurations.CLOUD_SQL_REGIONS_ALIASES_SECTION + "asia-east1", "asia-east1"); googleConfig.put(Configurations.COMPUTE_POLLING_TIMEOUT_KEY, "180"); googleConfig.put(Configurations.COMPUTE_MAX_POLLING_INTERVAL_KEY, "8"); return ConfigFactory.parseMap(googleConfig); } public static String buildImageUrl(String projectId, String image) { return ComputeUrls.buildGlobalUrl(projectId, "images", image); } public static String buildComputeInstanceUrl(String projectId, String zone, String instanceName) { return ComputeUrls.buildZonalUrl(projectId, zone, "instances", instanceName); } public static String buildDatabaseInstanceUrl(String projectId, String instanceName) {
return SQLUrls.buildGoogleCloudSQLApisUrl(projectId, "instances", instanceName);
maxpower47/DeliciousDroid
src/com/deliciousdroid/xml/SaxArticleParser.java
// Path: src/com/deliciousdroid/providers/ArticleContent.java // public static class Article { // // // private String url; // private String responseUrl; // private String content; // private String title; // private Spanned span; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Spanned getSpan() { // return span; // } // // public void setSpan(Spanned span) { // this.span = span; // } // // public String getResponseUrl() { // return responseUrl; // } // // public void setResponseUrl(String responseUrl) { // this.responseUrl = responseUrl; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // // // public Article() { // } // // public Article(String content, String title, String url, String responseUrl) { // this.content = content; // this.title = title; // this.url = url; // this.responseUrl = responseUrl; // } // // // public static Article valueOf(JSONObject userBookmark) { // try { // final String content = userBookmark.getString("content"); // final String title = userBookmark.getString("title"); // final String url = userBookmark.getString("url"); // final String responseUrl = userBookmark.getString("responseUrl"); // // return new Article(content, title, url, responseUrl); // } catch (final Exception ex) { // Log.i("User.Bookmark", "Error parsing JSON user object"); // } // return null; // } // }
import java.io.InputStream; import java.text.ParseException; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.util.Xml; import com.deliciousdroid.providers.ArticleContent.Article;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxArticleParser { private InputStream is; public SaxArticleParser(InputStream stream) { is = stream; }
// Path: src/com/deliciousdroid/providers/ArticleContent.java // public static class Article { // // // private String url; // private String responseUrl; // private String content; // private String title; // private Spanned span; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Spanned getSpan() { // return span; // } // // public void setSpan(Spanned span) { // this.span = span; // } // // public String getResponseUrl() { // return responseUrl; // } // // public void setResponseUrl(String responseUrl) { // this.responseUrl = responseUrl; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // // // public Article() { // } // // public Article(String content, String title, String url, String responseUrl) { // this.content = content; // this.title = title; // this.url = url; // this.responseUrl = responseUrl; // } // // // public static Article valueOf(JSONObject userBookmark) { // try { // final String content = userBookmark.getString("content"); // final String title = userBookmark.getString("title"); // final String url = userBookmark.getString("url"); // final String responseUrl = userBookmark.getString("responseUrl"); // // return new Article(content, title, url, responseUrl); // } catch (final Exception ex) { // Log.i("User.Bookmark", "Error parsing JSON user object"); // } // return null; // } // } // Path: src/com/deliciousdroid/xml/SaxArticleParser.java import java.io.InputStream; import java.text.ParseException; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.util.Xml; import com.deliciousdroid.providers.ArticleContent.Article; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxArticleParser { private InputStream is; public SaxArticleParser(InputStream stream) { is = stream; }
public Article parse() throws ParseException {
maxpower47/DeliciousDroid
src/com/deliciousdroid/receiver/AccountReceiver.java
// Path: src/com/deliciousdroid/service/AccountService.java // public class AccountService extends IntentService { // // private AccountManager mAccountManager; // // public AccountService() { // super("AccountService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // mAccountManager = AccountManager.get(this); // // Account[] accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE); // ArrayList<String> accountsList = new ArrayList<String>(); // for (int i = 0; i < accounts.length; i++) { // accountsList.add(accounts[i].name); // } // // BookmarkManager.TruncateBookmarks(accountsList, this, true); // TagManager.TruncateOldTags(accountsList, this); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.deliciousdroid.service.AccountService;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.receiver; public class AccountReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: src/com/deliciousdroid/service/AccountService.java // public class AccountService extends IntentService { // // private AccountManager mAccountManager; // // public AccountService() { // super("AccountService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // mAccountManager = AccountManager.get(this); // // Account[] accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE); // ArrayList<String> accountsList = new ArrayList<String>(); // for (int i = 0; i < accounts.length; i++) { // accountsList.add(accounts[i].name); // } // // BookmarkManager.TruncateBookmarks(accountsList, this, true); // TagManager.TruncateOldTags(accountsList, this); // } // } // Path: src/com/deliciousdroid/receiver/AccountReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.deliciousdroid.service.AccountService; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.receiver; public class AccountReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AccountService.class);
maxpower47/DeliciousDroid
src/com/deliciousdroid/client/Update.java
// Path: src/com/deliciousdroid/util/DateParser.java // public class DateParser { // // public static final TimeZone tz = TimeZone.getTimeZone("GMT"); // public static final Calendar c = Calendar.getInstance(tz); // // public static Date parse( String input ) throws java.text.ParseException { // // //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks // //things a bit. Before we go on we have to repair this. // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // //this is zero time so we need to add that TZ indicator for // if ( input.endsWith( "Z" ) ) { // input = input.substring( 0, input.length() - 1) + "GMT-00:00"; // } else { // int inset = 6; // // String s0 = input.substring( 0, input.length() - inset ); // String s1 = input.substring( input.length() - inset, input.length() ); // // input = s0 + "GMT" + s1; // } // // return df.parse( input ); // // } // // public static long parseTime( String input ) { // c.set(IntUtils.parseUInt(input.substring(0, 4)), // IntUtils.parseUInt(input.substring(5, 7)) - 1, // IntUtils.parseUInt(input.substring(8, 10)), // IntUtils.parseUInt(input.substring(11, 13)), // IntUtils.parseUInt(input.substring(14, 16)), // IntUtils.parseUInt(input.substring(17, 19))); // // return c.getTimeInMillis(); // } // // public static String toString( Date date ) { // // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // TimeZone tz = TimeZone.getTimeZone( "UTC" ); // // df.setTimeZone( tz ); // // String output = df.format( date ); // // int inset0 = 9; // int inset1 = 6; // // String s0 = output.substring( 0, output.length() - inset0 ); // String s1 = output.substring( output.length() - inset1, output.length() ); // // String result = s0 + s1; // // result = result.replaceAll( "UTC", "+00:00" ); // // return result; // // } // }
import com.deliciousdroid.util.DateParser;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.client; public class Update { private long lastUpdate; public long getLastUpdate(){ return lastUpdate; } public Update(long update){ lastUpdate = update; } public static Update valueOf(String updateResponse){ try { int start = updateResponse.indexOf("<update"); int end = updateResponse.indexOf("/>", start); String updateElement = updateResponse.substring(start, end); int timestart = updateElement.indexOf("time="); int timeend = updateElement.indexOf("\"", timestart + 7); String time = updateElement.substring(timestart + 6, timeend);
// Path: src/com/deliciousdroid/util/DateParser.java // public class DateParser { // // public static final TimeZone tz = TimeZone.getTimeZone("GMT"); // public static final Calendar c = Calendar.getInstance(tz); // // public static Date parse( String input ) throws java.text.ParseException { // // //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks // //things a bit. Before we go on we have to repair this. // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // //this is zero time so we need to add that TZ indicator for // if ( input.endsWith( "Z" ) ) { // input = input.substring( 0, input.length() - 1) + "GMT-00:00"; // } else { // int inset = 6; // // String s0 = input.substring( 0, input.length() - inset ); // String s1 = input.substring( input.length() - inset, input.length() ); // // input = s0 + "GMT" + s1; // } // // return df.parse( input ); // // } // // public static long parseTime( String input ) { // c.set(IntUtils.parseUInt(input.substring(0, 4)), // IntUtils.parseUInt(input.substring(5, 7)) - 1, // IntUtils.parseUInt(input.substring(8, 10)), // IntUtils.parseUInt(input.substring(11, 13)), // IntUtils.parseUInt(input.substring(14, 16)), // IntUtils.parseUInt(input.substring(17, 19))); // // return c.getTimeInMillis(); // } // // public static String toString( Date date ) { // // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // TimeZone tz = TimeZone.getTimeZone( "UTC" ); // // df.setTimeZone( tz ); // // String output = df.format( date ); // // int inset0 = 9; // int inset1 = 6; // // String s0 = output.substring( 0, output.length() - inset0 ); // String s1 = output.substring( output.length() - inset1, output.length() ); // // String result = s0 + s1; // // result = result.replaceAll( "UTC", "+00:00" ); // // return result; // // } // } // Path: src/com/deliciousdroid/client/Update.java import com.deliciousdroid.util.DateParser; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.client; public class Update { private long lastUpdate; public long getLastUpdate(){ return lastUpdate; } public Update(long update){ lastUpdate = update; } public static Update valueOf(String updateResponse){ try { int start = updateResponse.indexOf("<update"); int end = updateResponse.indexOf("/>", start); String updateElement = updateResponse.substring(start, end); int timestart = updateElement.indexOf("time="); int timeend = updateElement.indexOf("\"", timestart + 7); String time = updateElement.substring(timestart + 6, timeend);
long updateTime = DateParser.parse(time).getTime();
maxpower47/DeliciousDroid
src/com/deliciousdroid/xml/SaxTagParser.java
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // // Path: src/com/deliciousdroid/util/IntUtils.java // public class IntUtils { // public static int parseUInt(final String s) // { // // Check for a sign. // int num = 0; // final int len = s.length(); // final char ch = s.charAt(0); // // num = '0' - ch; // // // Build the number. // int i = 1; // while ( i < len ) // num = num * 10 + '0' - s.charAt(i++); // // return -1 * num; // } // }
import android.util.Log; import android.util.Xml; import com.deliciousdroid.providers.TagContent.Tag; import com.deliciousdroid.util.IntUtils; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxTagParser { private InputStream is; public SaxTagParser(InputStream stream) { is = stream; }
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // // Path: src/com/deliciousdroid/util/IntUtils.java // public class IntUtils { // public static int parseUInt(final String s) // { // // Check for a sign. // int num = 0; // final int len = s.length(); // final char ch = s.charAt(0); // // num = '0' - ch; // // // Build the number. // int i = 1; // while ( i < len ) // num = num * 10 + '0' - s.charAt(i++); // // return -1 * num; // } // } // Path: src/com/deliciousdroid/xml/SaxTagParser.java import android.util.Log; import android.util.Xml; import com.deliciousdroid.providers.TagContent.Tag; import com.deliciousdroid.util.IntUtils; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxTagParser { private InputStream is; public SaxTagParser(InputStream stream) { is = stream; }
public ArrayList<Tag> parse() throws ParseException {
maxpower47/DeliciousDroid
src/com/deliciousdroid/xml/SaxTagParser.java
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // // Path: src/com/deliciousdroid/util/IntUtils.java // public class IntUtils { // public static int parseUInt(final String s) // { // // Check for a sign. // int num = 0; // final int len = s.length(); // final char ch = s.charAt(0); // // num = '0' - ch; // // // Build the number. // int i = 1; // while ( i < len ) // num = num * 10 + '0' - s.charAt(i++); // // return -1 * num; // } // }
import android.util.Log; import android.util.Xml; import com.deliciousdroid.providers.TagContent.Tag; import com.deliciousdroid.util.IntUtils; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxTagParser { private InputStream is; public SaxTagParser(InputStream stream) { is = stream; } public ArrayList<Tag> parse() throws ParseException { final Tag currentTag = new Tag(); RootElement root = new RootElement("tags"); final ArrayList<Tag> tags = new ArrayList<Tag>(); root.getChild("tag").setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { String count = attributes.getValue("", "count"); String tag = attributes.getValue("", "tag"); if(count != null) {
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // // Path: src/com/deliciousdroid/util/IntUtils.java // public class IntUtils { // public static int parseUInt(final String s) // { // // Check for a sign. // int num = 0; // final int len = s.length(); // final char ch = s.charAt(0); // // num = '0' - ch; // // // Build the number. // int i = 1; // while ( i < len ) // num = num * 10 + '0' - s.charAt(i++); // // return -1 * num; // } // } // Path: src/com/deliciousdroid/xml/SaxTagParser.java import android.util.Log; import android.util.Xml; import com.deliciousdroid.providers.TagContent.Tag; import com.deliciousdroid.util.IntUtils; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxTagParser { private InputStream is; public SaxTagParser(InputStream stream) { is = stream; } public ArrayList<Tag> parse() throws ParseException { final Tag currentTag = new Tag(); RootElement root = new RootElement("tags"); final ArrayList<Tag> tags = new ArrayList<Tag>(); root.getChild("tag").setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { String count = attributes.getValue("", "count"); String tag = attributes.getValue("", "tag"); if(count != null) {
currentTag.setCount(IntUtils.parseUInt(count));
maxpower47/DeliciousDroid
src/com/deliciousdroid/client/User.java
// Path: src/com/deliciousdroid/util/DateParser.java // public class DateParser { // // public static final TimeZone tz = TimeZone.getTimeZone("GMT"); // public static final Calendar c = Calendar.getInstance(tz); // // public static Date parse( String input ) throws java.text.ParseException { // // //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks // //things a bit. Before we go on we have to repair this. // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // //this is zero time so we need to add that TZ indicator for // if ( input.endsWith( "Z" ) ) { // input = input.substring( 0, input.length() - 1) + "GMT-00:00"; // } else { // int inset = 6; // // String s0 = input.substring( 0, input.length() - inset ); // String s1 = input.substring( input.length() - inset, input.length() ); // // input = s0 + "GMT" + s1; // } // // return df.parse( input ); // // } // // public static long parseTime( String input ) { // c.set(IntUtils.parseUInt(input.substring(0, 4)), // IntUtils.parseUInt(input.substring(5, 7)) - 1, // IntUtils.parseUInt(input.substring(8, 10)), // IntUtils.parseUInt(input.substring(11, 13)), // IntUtils.parseUInt(input.substring(14, 16)), // IntUtils.parseUInt(input.substring(17, 19))); // // return c.getTimeInMillis(); // } // // public static String toString( Date date ) { // // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // TimeZone tz = TimeZone.getTimeZone( "UTC" ); // // df.setTimeZone( tz ); // // String output = df.format( date ); // // int inset0 = 9; // int inset1 = 6; // // String s0 = output.substring( 0, output.length() - inset0 ); // String s1 = output.substring( output.length() - inset1, output.length() ); // // String result = s0 + s1; // // result = result.replaceAll( "UTC", "+00:00" ); // // return result; // // } // }
import android.util.Log; import org.json.JSONObject; import com.deliciousdroid.util.DateParser; import java.util.Date;
*/ public static class Status { private final String mUserName; private final String mStatus; private final Date mTimestamp; public String getUserName() { return mUserName; } public String getStatus() { return mStatus; } public Date getTimeStamp() { return mTimestamp; } public Status(String userName, String status, Date timestamp) { mUserName = userName; mStatus = status; mTimestamp = timestamp; } public static User.Status valueOf(JSONObject userStatus) { try { final String userName = userStatus.getString("a"); final String status = userStatus.getString("d"); final String date = userStatus.getString("dt");
// Path: src/com/deliciousdroid/util/DateParser.java // public class DateParser { // // public static final TimeZone tz = TimeZone.getTimeZone("GMT"); // public static final Calendar c = Calendar.getInstance(tz); // // public static Date parse( String input ) throws java.text.ParseException { // // //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks // //things a bit. Before we go on we have to repair this. // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // //this is zero time so we need to add that TZ indicator for // if ( input.endsWith( "Z" ) ) { // input = input.substring( 0, input.length() - 1) + "GMT-00:00"; // } else { // int inset = 6; // // String s0 = input.substring( 0, input.length() - inset ); // String s1 = input.substring( input.length() - inset, input.length() ); // // input = s0 + "GMT" + s1; // } // // return df.parse( input ); // // } // // public static long parseTime( String input ) { // c.set(IntUtils.parseUInt(input.substring(0, 4)), // IntUtils.parseUInt(input.substring(5, 7)) - 1, // IntUtils.parseUInt(input.substring(8, 10)), // IntUtils.parseUInt(input.substring(11, 13)), // IntUtils.parseUInt(input.substring(14, 16)), // IntUtils.parseUInt(input.substring(17, 19))); // // return c.getTimeInMillis(); // } // // public static String toString( Date date ) { // // SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" ); // // TimeZone tz = TimeZone.getTimeZone( "UTC" ); // // df.setTimeZone( tz ); // // String output = df.format( date ); // // int inset0 = 9; // int inset1 = 6; // // String s0 = output.substring( 0, output.length() - inset0 ); // String s1 = output.substring( output.length() - inset1, output.length() ); // // String result = s0 + s1; // // result = result.replaceAll( "UTC", "+00:00" ); // // return result; // // } // } // Path: src/com/deliciousdroid/client/User.java import android.util.Log; import org.json.JSONObject; import com.deliciousdroid.util.DateParser; import java.util.Date; */ public static class Status { private final String mUserName; private final String mStatus; private final Date mTimestamp; public String getUserName() { return mUserName; } public String getStatus() { return mStatus; } public Date getTimeStamp() { return mTimestamp; } public Status(String userName, String status, Date timestamp) { mUserName = userName; mStatus = status; mTimestamp = timestamp; } public static User.Status valueOf(JSONObject userStatus) { try { final String userName = userStatus.getString("a"); final String status = userStatus.getString("d"); final String date = userStatus.getString("dt");
Date timestamp = DateParser.parse(date);
maxpower47/DeliciousDroid
src/com/deliciousdroid/platform/TagManager.java
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // }
import java.util.ArrayList; import com.deliciousdroid.providers.TagContent.Tag; import android.content.ContentValues; import android.content.Context; import android.support.v4.content.CursorLoader; import android.database.Cursor; import android.text.TextUtils;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.platform; public class TagManager { public static CursorLoader GetTags(String account, String sortorder, Context context) {
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // Path: src/com/deliciousdroid/platform/TagManager.java import java.util.ArrayList; import com.deliciousdroid.providers.TagContent.Tag; import android.content.ContentValues; import android.content.Context; import android.support.v4.content.CursorLoader; import android.database.Cursor; import android.text.TextUtils; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.platform; public class TagManager { public static CursorLoader GetTags(String account, String sortorder, Context context) {
final String[] projection = new String[] {Tag._ID, Tag.Name, Tag.Count};
maxpower47/DeliciousDroid
src/com/deliciousdroid/util/SyncUtils.java
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // } // // Path: src/com/deliciousdroid/syncadapter/PeriodicSyncReceiver.java // public final class PeriodicSyncReceiver extends BroadcastReceiver { // // private static final String KEY_AUTHORITY = "authority"; // // private static final String KEY_USERDATA = "userdata"; // // public static Intent createIntent(Context context, String authority, Bundle extras) { // Intent intent = new Intent(context, PeriodicSyncReceiver.class); // intent.putExtra(KEY_AUTHORITY, authority); // intent.putExtra(KEY_USERDATA, extras); // return intent; // } // // public static PendingIntent createPendingIntent(Context context, String authority, Bundle extras) { // int requestCode = 0; // Intent intent = createIntent(context, authority, extras); // int flags = 0; // return PendingIntent.getBroadcast(context, requestCode, intent, flags); // } // // @Override // public void onReceive(Context context, Intent intent) { // String authority = intent.getStringExtra(KEY_AUTHORITY); // Bundle extras = intent.getBundleExtra(KEY_USERDATA); // // ContentResolver.requestSync(null, authority, extras); // } // }
import android.content.Context; import android.os.Bundle; import android.os.SystemClock; import com.deliciousdroid.Constants; import com.deliciousdroid.syncadapter.PeriodicSyncReceiver; import android.annotation.TargetApi; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.util; public class SyncUtils { @TargetApi(8) public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) { long pollFrequencyMsec = frequency * 60000; if(android.os.Build.VERSION.SDK_INT < 8) { AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); int type = AlarmManager.ELAPSED_REALTIME_WAKEUP; long triggerAtTime = SystemClock.elapsedRealtime() + pollFrequencyMsec; long interval = pollFrequencyMsec;
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // } // // Path: src/com/deliciousdroid/syncadapter/PeriodicSyncReceiver.java // public final class PeriodicSyncReceiver extends BroadcastReceiver { // // private static final String KEY_AUTHORITY = "authority"; // // private static final String KEY_USERDATA = "userdata"; // // public static Intent createIntent(Context context, String authority, Bundle extras) { // Intent intent = new Intent(context, PeriodicSyncReceiver.class); // intent.putExtra(KEY_AUTHORITY, authority); // intent.putExtra(KEY_USERDATA, extras); // return intent; // } // // public static PendingIntent createPendingIntent(Context context, String authority, Bundle extras) { // int requestCode = 0; // Intent intent = createIntent(context, authority, extras); // int flags = 0; // return PendingIntent.getBroadcast(context, requestCode, intent, flags); // } // // @Override // public void onReceive(Context context, Intent intent) { // String authority = intent.getStringExtra(KEY_AUTHORITY); // Bundle extras = intent.getBundleExtra(KEY_USERDATA); // // ContentResolver.requestSync(null, authority, extras); // } // } // Path: src/com/deliciousdroid/util/SyncUtils.java import android.content.Context; import android.os.Bundle; import android.os.SystemClock; import com.deliciousdroid.Constants; import com.deliciousdroid.syncadapter.PeriodicSyncReceiver; import android.annotation.TargetApi; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.util; public class SyncUtils { @TargetApi(8) public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) { long pollFrequencyMsec = frequency * 60000; if(android.os.Build.VERSION.SDK_INT < 8) { AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); int type = AlarmManager.ELAPSED_REALTIME_WAKEUP; long triggerAtTime = SystemClock.elapsedRealtime() + pollFrequencyMsec; long interval = pollFrequencyMsec;
PendingIntent operation = PeriodicSyncReceiver.createPendingIntent(context, authority, extras);
maxpower47/DeliciousDroid
src/com/deliciousdroid/util/SyncUtils.java
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // } // // Path: src/com/deliciousdroid/syncadapter/PeriodicSyncReceiver.java // public final class PeriodicSyncReceiver extends BroadcastReceiver { // // private static final String KEY_AUTHORITY = "authority"; // // private static final String KEY_USERDATA = "userdata"; // // public static Intent createIntent(Context context, String authority, Bundle extras) { // Intent intent = new Intent(context, PeriodicSyncReceiver.class); // intent.putExtra(KEY_AUTHORITY, authority); // intent.putExtra(KEY_USERDATA, extras); // return intent; // } // // public static PendingIntent createPendingIntent(Context context, String authority, Bundle extras) { // int requestCode = 0; // Intent intent = createIntent(context, authority, extras); // int flags = 0; // return PendingIntent.getBroadcast(context, requestCode, intent, flags); // } // // @Override // public void onReceive(Context context, Intent intent) { // String authority = intent.getStringExtra(KEY_AUTHORITY); // Bundle extras = intent.getBundleExtra(KEY_USERDATA); // // ContentResolver.requestSync(null, authority, extras); // } // }
import android.content.Context; import android.os.Bundle; import android.os.SystemClock; import com.deliciousdroid.Constants; import com.deliciousdroid.syncadapter.PeriodicSyncReceiver; import android.annotation.TargetApi; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.util; public class SyncUtils { @TargetApi(8) public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) { long pollFrequencyMsec = frequency * 60000; if(android.os.Build.VERSION.SDK_INT < 8) { AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); int type = AlarmManager.ELAPSED_REALTIME_WAKEUP; long triggerAtTime = SystemClock.elapsedRealtime() + pollFrequencyMsec; long interval = pollFrequencyMsec; PendingIntent operation = PeriodicSyncReceiver.createPendingIntent(context, authority, extras); manager.setInexactRepeating(type, triggerAtTime, interval, operation); } else { AccountManager am = AccountManager.get(context);
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // } // // Path: src/com/deliciousdroid/syncadapter/PeriodicSyncReceiver.java // public final class PeriodicSyncReceiver extends BroadcastReceiver { // // private static final String KEY_AUTHORITY = "authority"; // // private static final String KEY_USERDATA = "userdata"; // // public static Intent createIntent(Context context, String authority, Bundle extras) { // Intent intent = new Intent(context, PeriodicSyncReceiver.class); // intent.putExtra(KEY_AUTHORITY, authority); // intent.putExtra(KEY_USERDATA, extras); // return intent; // } // // public static PendingIntent createPendingIntent(Context context, String authority, Bundle extras) { // int requestCode = 0; // Intent intent = createIntent(context, authority, extras); // int flags = 0; // return PendingIntent.getBroadcast(context, requestCode, intent, flags); // } // // @Override // public void onReceive(Context context, Intent intent) { // String authority = intent.getStringExtra(KEY_AUTHORITY); // Bundle extras = intent.getBundleExtra(KEY_USERDATA); // // ContentResolver.requestSync(null, authority, extras); // } // } // Path: src/com/deliciousdroid/util/SyncUtils.java import android.content.Context; import android.os.Bundle; import android.os.SystemClock; import com.deliciousdroid.Constants; import com.deliciousdroid.syncadapter.PeriodicSyncReceiver; import android.annotation.TargetApi; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.util; public class SyncUtils { @TargetApi(8) public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) { long pollFrequencyMsec = frequency * 60000; if(android.os.Build.VERSION.SDK_INT < 8) { AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); int type = AlarmManager.ELAPSED_REALTIME_WAKEUP; long triggerAtTime = SystemClock.elapsedRealtime() + pollFrequencyMsec; long interval = pollFrequencyMsec; PendingIntent operation = PeriodicSyncReceiver.createPendingIntent(context, authority, extras); manager.setInexactRepeating(type, triggerAtTime, interval, operation); } else { AccountManager am = AccountManager.get(context);
Account[] accounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
maxpower47/DeliciousDroid
src/com/deliciousdroid/xml/SaxBundleParser.java
// Path: src/com/deliciousdroid/providers/BundleContent.java // public static class Bundle implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/bundle"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.bundles"; // // public static final String Name = "NAME"; // public static final String Tags = "TAGS"; // public static final String Account = "ACCOUNT"; // // private String mName; // private int mId = 0; // private String mTags; // private String mAccount; // // public int getId(){ // return mId; // } // // public void setId(int id){ // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getTagString(){ // return mTags; // } // // public void setTagString(String tags) { // mTags = tags; // } // // public ArrayList<String> getTags(){ // ArrayList<String> result = new ArrayList<String>(); // for(String s : this.getTagString().split(" ")) { // result.add(s); // } // // return result; // } // // public String getAccount(){ // return mAccount; // } // // public void setAccount(String account) { // mAccount = account; // } // // // public Bundle() { // // } // // public Bundle(String name) { // mName = name; // } // // public Bundle(String name, String tags) { // mName = name; // mTags = tags; // } // // public Bundle copy(){ // Bundle t = new Bundle(); // t.mId = this.mId; // t.mName = this.mName; // t.mTags = this.mTags; // return t; // } // }
import com.deliciousdroid.providers.BundleContent.Bundle; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Xml;
/* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxBundleParser { private InputStream is; public SaxBundleParser(InputStream stream) { is = stream; }
// Path: src/com/deliciousdroid/providers/BundleContent.java // public static class Bundle implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/bundle"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.bundles"; // // public static final String Name = "NAME"; // public static final String Tags = "TAGS"; // public static final String Account = "ACCOUNT"; // // private String mName; // private int mId = 0; // private String mTags; // private String mAccount; // // public int getId(){ // return mId; // } // // public void setId(int id){ // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getTagString(){ // return mTags; // } // // public void setTagString(String tags) { // mTags = tags; // } // // public ArrayList<String> getTags(){ // ArrayList<String> result = new ArrayList<String>(); // for(String s : this.getTagString().split(" ")) { // result.add(s); // } // // return result; // } // // public String getAccount(){ // return mAccount; // } // // public void setAccount(String account) { // mAccount = account; // } // // // public Bundle() { // // } // // public Bundle(String name) { // mName = name; // } // // public Bundle(String name, String tags) { // mName = name; // mTags = tags; // } // // public Bundle copy(){ // Bundle t = new Bundle(); // t.mId = this.mId; // t.mName = this.mName; // t.mTags = this.mTags; // return t; // } // } // Path: src/com/deliciousdroid/xml/SaxBundleParser.java import com.deliciousdroid.providers.BundleContent.Bundle; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import org.xml.sax.Attributes; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Xml; /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.xml; public class SaxBundleParser { private InputStream is; public SaxBundleParser(InputStream stream) { is = stream; }
public ArrayList<Bundle> parse() throws ParseException {
maxpower47/DeliciousDroid
src/com/deliciousdroid/providers/BookmarkContent.java
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // }
import java.io.Serializable; import java.util.ArrayList; import com.deliciousdroid.providers.TagContent.Tag; import android.net.Uri; import android.provider.BaseColumns;
} public void setUrl(String url) { mUrl = url; } public String getDescription() { return mDescription; } public void setDescription(String desc) { mDescription = desc; } public String getNotes(){ return mNotes == null ? "" : mNotes; } public void setNotes(String notes) { mNotes = notes; } public String getTagString(){ return mTags; } public void setTagString(String tags){ mTags = tags; }
// Path: src/com/deliciousdroid/providers/TagContent.java // public static class Tag implements BaseColumns { // public static final Uri CONTENT_URI = Uri.parse("content://" + // BookmarkContentProvider.AUTHORITY + "/tag"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.deliciousdroid.tags"; // // public static final String Name = "NAME"; // public static final String Count = "COUNT"; // public static final String Account = "ACCOUNT"; // // private String mTagName; // private int mCount = 0; // private int mId = 0; // private String mType = null; // // public int getId(){ // return mId; // } // // public String getTagName() { // return mTagName; // } // // public void setTagName(String tagName) { // mTagName = tagName; // } // // public int getCount() { // return mCount; // } // // public String getType() { // return mType; // } // // public void setType(String type) { // mType = type; // } // // public void setCount(int count) { // mCount = count; // } // // public Tag() { // // } // // public Tag(String tagName) { // mTagName = tagName; // } // // public Tag(String tagName, int count) { // mTagName = tagName; // mCount = count; // } // // public Tag copy(){ // Tag t = new Tag(); // t.mCount = this.mCount; // t.mId = this.mId; // t.mTagName = this.mTagName; // t.mType = this.mType; // return t; // } // } // Path: src/com/deliciousdroid/providers/BookmarkContent.java import java.io.Serializable; import java.util.ArrayList; import com.deliciousdroid.providers.TagContent.Tag; import android.net.Uri; import android.provider.BaseColumns; } public void setUrl(String url) { mUrl = url; } public String getDescription() { return mDescription; } public void setDescription(String desc) { mDescription = desc; } public String getNotes(){ return mNotes == null ? "" : mNotes; } public void setNotes(String notes) { mNotes = notes; } public String getTagString(){ return mTags; } public void setTagString(String tags){ mTags = tags; }
public ArrayList<Tag> getTags(){
maxpower47/DeliciousDroid
src/com/deliciousdroid/platform/ContactOperations.java
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // }
import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.text.TextUtils; import android.util.Log; import com.deliciousdroid.R; import com.deliciousdroid.Constants; import android.content.ContentProviderOperation; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone;
return new ContactOperations(context, userName, accountName, batchOperation); } /** * Returns an instance of ContactOperations for updating existing contact in * the platform contacts provider. * * @param context the Authenticator Activity context * @param rawContactId the unique Id of the existing rawContact * @return instance of ContactOperations */ public static ContactOperations updateExistingContact(Context context, long rawContactId, BatchOperation batchOperation) { return new ContactOperations(context, rawContactId, batchOperation); } public ContactOperations(Context context, BatchOperation batchOperation) { mValues = new ContentValues(); mYield = true; mContext = context; mBatchOperation = batchOperation; } public ContactOperations(Context context, String userName, String accountName, BatchOperation batchOperation) { this(context, batchOperation); mBackReference = mBatchOperation.size(); mIsNewContact = true; mValues.put(RawContacts.SOURCE_ID, userName);
// Path: src/com/deliciousdroid/Constants.java // public class Constants { // // /** // * Account type string. // */ // public static final String ACCOUNT_TYPE = "com.deliciousdroid"; // // public static final Uri CONTENT_URI_BASE = Uri.parse("content://com.deliciousdroid"); // // public static final String CONTENT_SCHEME = "content"; // // public static final String EXTRA_DESCRIPTION = "com.deliciousdroid.bookmark.description"; // public static final String EXTRA_NOTES = "com.deliciousdroid.bookmark.notes"; // public static final String EXTRA_TAGS = "com.deliciousdroid.bookmark.tags"; // public static final String EXTRA_PRIVATE = "com.deliciousdroid.bookmark.private"; // public static final String EXTRA_ERROR = "com.deliciousdroid.bookmark.error"; // public static final String EXTRA_TIME = "com.deliciousdroid.bookmark.time"; // public static final String EXTRA_UPDATE = "com.deliciousdroid.bookmark.update"; // // public static final String TEXT_EXTRACTOR_URL = "http://viewtext.org/api/text?url="; // // public static final String SYNC_MARKER_KEY = "com.deliciousdroid.BookmarkSyncAdapter.marker"; // // public static final int BOOKMARK_PAGE_SIZE = 500; // // public static final String ACTION_SEARCH_SUGGESTION = "com.deliciousdroid.intent.action.SearchSuggestion"; // // public static final String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; // // /** // * Authtoken type string. // */ // public static final String AUTHTOKEN_TYPE = "com.deliciousdroid"; // // public static final String AUTH_PREFS_NAME = "com.deliciousdroid.auth"; // // public static final String PREFS_AUTH_TYPE = "authentication_type"; // public static final String AUTH_TYPE_DELICIOUS = "delicious"; // // public static final String GPL_URL = "http://www.gnu.org/licenses/gpl-3.0.txt"; // public static final String MANUAL_URL = "http://code.google.com/p/deliciousdroid/wiki/Manual"; // public static final String DONATION_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6ERJRC6SWL9ZC"; // // public static enum BookmarkViewType {VIEW, READ, WEB}; // } // Path: src/com/deliciousdroid/platform/ContactOperations.java import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.text.TextUtils; import android.util.Log; import com.deliciousdroid.R; import com.deliciousdroid.Constants; import android.content.ContentProviderOperation; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; return new ContactOperations(context, userName, accountName, batchOperation); } /** * Returns an instance of ContactOperations for updating existing contact in * the platform contacts provider. * * @param context the Authenticator Activity context * @param rawContactId the unique Id of the existing rawContact * @return instance of ContactOperations */ public static ContactOperations updateExistingContact(Context context, long rawContactId, BatchOperation batchOperation) { return new ContactOperations(context, rawContactId, batchOperation); } public ContactOperations(Context context, BatchOperation batchOperation) { mValues = new ContentValues(); mYield = true; mContext = context; mBatchOperation = batchOperation; } public ContactOperations(Context context, String userName, String accountName, BatchOperation batchOperation) { this(context, batchOperation); mBackReference = mBatchOperation.size(); mIsNewContact = true; mValues.put(RawContacts.SOURCE_ID, userName);
mValues.put(RawContacts.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
dtanzer/jobjectformatter
src/test/java/net/davidtanzer/jobjectformatter/ObjectFormatterTest.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatter.java // public class JsonObjectStringFormatter extends AbstractObjectStringFormatter { // private static final Set<Class<?>> unescapedTypes = new HashSet<Class<?>>() {{ // add(Integer.class); // add(Short.class); // add(Float.class); // add(Double.class); // add(Boolean.class); // // add(int.class); // add(short.class); // add(float.class); // add(double.class); // add(boolean.class); // }}; // private final DisplayClassName displayClassName; // private final FormatGrouped formatGrouped; // // /** // * Creates a new JsonObjectStringFormatter with the default configuration. // * // * The default configuraiton is: // * <ul> // * <li>Group objects by their declaring class.</li> // * <li>Only display the class name when not grouping objects by their declaring class.</li> // * </ul> // * // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // */ // public JsonObjectStringFormatter() { // this(FormatGrouped.BY_CLASS, DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS); // } // // /** // * Creates a new JsonObjectStringFormatter with a given grouping configuration, leaving {@link net.davidtanzer.jobjectformatter.formatter.DisplayClassName} // * at the default configuration. // * // * Refer to the documentation of the no-args constructor for the default configuration. // * // * @param formatGrouped The configuration for grouping the values. // // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // * @see JsonObjectStringFormatter#JsonObjectStringFormatter() // */ // public JsonObjectStringFormatter(final FormatGrouped formatGrouped) { // this(formatGrouped, DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS); // } // // // /** // * Creates a new JsonObjectStringFormatter with a given grouping configuration and display-class-name configuration. // * // * @param formatGrouped The configuration for grouping the values. // * @param displayClassName The configuration for displaying the class name. // * // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // */ // public JsonObjectStringFormatter(final FormatGrouped formatGrouped, final DisplayClassName displayClassName) { // super(formatGrouped); // // if(displayClassName == null) { // throw new IllegalArgumentException("Parameter displayClassName must not be null."); // } // this.formatGrouped = formatGrouped; // this.displayClassName = displayClassName; // } // // @Override // protected void appendSingleValue(final StringBuilder result, final ValueInfo value) { // result.append("\"").append(value.getPropertyName()).append("\": "); // if(!unescapedTypes.contains(value.getPropertyType())) { // result.append("\""); // } // result.append(value.getValue()); // if(!unescapedTypes.contains(value.getPropertyType())) { // result.append("\""); // } // } // // @Override // protected void startFormattedString(final StringBuilder result, final ObjectValuesInfo info) { // result.append("{"); // if(displayClassName == DisplayClassName.ALWAYS || // (displayClassName == DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS) && formatGrouped != FormatGrouped.BY_CLASS) { // result.append("\"class\": \"").append(info.getType().getSimpleName()).append("\"").append(getValueSeparator()); // } // } // // @Override // protected void endFormattedString(final StringBuilder result, final ObjectValuesInfo info) { // result.append("}"); // } // // @Override // protected void startValueGroup(final StringBuilder result, final GroupedValuesInfo groupedValuesInfo) { // result.append("\"").append(groupedValuesInfo.getGroupName()).append("\": {"); // } // // @Override // protected void endValueGroup(final StringBuilder result) { // result.append("}"); // } // }
import net.davidtanzer.jobjectformatter.formatter.JsonObjectStringFormatter; import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter; public class ObjectFormatterTest { @Before public void setup() {
// Path: src/main/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatter.java // public class JsonObjectStringFormatter extends AbstractObjectStringFormatter { // private static final Set<Class<?>> unescapedTypes = new HashSet<Class<?>>() {{ // add(Integer.class); // add(Short.class); // add(Float.class); // add(Double.class); // add(Boolean.class); // // add(int.class); // add(short.class); // add(float.class); // add(double.class); // add(boolean.class); // }}; // private final DisplayClassName displayClassName; // private final FormatGrouped formatGrouped; // // /** // * Creates a new JsonObjectStringFormatter with the default configuration. // * // * The default configuraiton is: // * <ul> // * <li>Group objects by their declaring class.</li> // * <li>Only display the class name when not grouping objects by their declaring class.</li> // * </ul> // * // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // */ // public JsonObjectStringFormatter() { // this(FormatGrouped.BY_CLASS, DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS); // } // // /** // * Creates a new JsonObjectStringFormatter with a given grouping configuration, leaving {@link net.davidtanzer.jobjectformatter.formatter.DisplayClassName} // * at the default configuration. // * // * Refer to the documentation of the no-args constructor for the default configuration. // * // * @param formatGrouped The configuration for grouping the values. // // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // * @see JsonObjectStringFormatter#JsonObjectStringFormatter() // */ // public JsonObjectStringFormatter(final FormatGrouped formatGrouped) { // this(formatGrouped, DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS); // } // // // /** // * Creates a new JsonObjectStringFormatter with a given grouping configuration and display-class-name configuration. // * // * @param formatGrouped The configuration for grouping the values. // * @param displayClassName The configuration for displaying the class name. // * // * @see net.davidtanzer.jobjectformatter.formatter.FormatGrouped // * @see net.davidtanzer.jobjectformatter.formatter.DisplayClassName // */ // public JsonObjectStringFormatter(final FormatGrouped formatGrouped, final DisplayClassName displayClassName) { // super(formatGrouped); // // if(displayClassName == null) { // throw new IllegalArgumentException("Parameter displayClassName must not be null."); // } // this.formatGrouped = formatGrouped; // this.displayClassName = displayClassName; // } // // @Override // protected void appendSingleValue(final StringBuilder result, final ValueInfo value) { // result.append("\"").append(value.getPropertyName()).append("\": "); // if(!unescapedTypes.contains(value.getPropertyType())) { // result.append("\""); // } // result.append(value.getValue()); // if(!unescapedTypes.contains(value.getPropertyType())) { // result.append("\""); // } // } // // @Override // protected void startFormattedString(final StringBuilder result, final ObjectValuesInfo info) { // result.append("{"); // if(displayClassName == DisplayClassName.ALWAYS || // (displayClassName == DisplayClassName.WHEN_NOT_GROUPED_BY_CLASS) && formatGrouped != FormatGrouped.BY_CLASS) { // result.append("\"class\": \"").append(info.getType().getSimpleName()).append("\"").append(getValueSeparator()); // } // } // // @Override // protected void endFormattedString(final StringBuilder result, final ObjectValuesInfo info) { // result.append("}"); // } // // @Override // protected void startValueGroup(final StringBuilder result, final GroupedValuesInfo groupedValuesInfo) { // result.append("\"").append(groupedValuesInfo.getGroupName()).append("\": {"); // } // // @Override // protected void endValueGroup(final StringBuilder result) { // result.append("}"); // } // } // Path: src/test/java/net/davidtanzer/jobjectformatter/ObjectFormatterTest.java import net.davidtanzer.jobjectformatter.formatter.JsonObjectStringFormatter; import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter; public class ObjectFormatterTest { @Before public void setup() {
ObjectFormatter.configureGenerator(new FormattedStringGenerator(new JsonObjectStringFormatter()));
dtanzer/jobjectformatter
src/test/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfoTransitivityTest.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // }
import net.davidtanzer.jobjectformatter.annotations.Formatted; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; public class TypeInfoTransitivityTest { private TypeInfoCache typeInfoCache; @Before public void setup() { typeInfoCache = new TypeInfoCache(); } @Test public void allTypeInfosFromJavaPackagesAreTransitive() { final TypeInfo info = typeInfoCache.typeInfoFor(SimpleObject.class); List<PropertyInfo> propertyInfos = info.classInfos().get(0).fieldInfos(); assertThat(propertyInfos, hasItem(allOf( hasProperty("name", is("foo")),
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // } // Path: src/test/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfoTransitivityTest.java import net.davidtanzer.jobjectformatter.annotations.Formatted; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; public class TypeInfoTransitivityTest { private TypeInfoCache typeInfoCache; @Before public void setup() { typeInfoCache = new TypeInfoCache(); } @Test public void allTypeInfosFromJavaPackagesAreTransitive() { final TypeInfo info = typeInfoCache.typeInfoFor(SimpleObject.class); List<PropertyInfo> propertyInfos = info.classInfos().get(0).fieldInfos(); assertThat(propertyInfos, hasItem(allOf( hasProperty("name", is("foo")),
hasProperty("transitiveIncludeOfTarget", is(TransitiveInclude.ALL_FIELDS)))));
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/examples/formatters/FormattersExample.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // }
import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*; import net.davidtanzer.jobjectformatter.formatter.*; import java.util.Arrays; import java.util.List;
package net.davidtanzer.jobjectformatter.examples.formatters; public class FormattersExample { public static void main(String[] args) { Role role = new Role("admin"); Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address, "jdoe", Arrays.asList(role)); address.setOwner(person);
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/examples/formatters/FormattersExample.java import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*; import net.davidtanzer.jobjectformatter.formatter.*; import java.util.Arrays; import java.util.List; package net.davidtanzer.jobjectformatter.examples.formatters; public class FormattersExample { public static void main(String[] args) { Role role = new Role("admin"); Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address, "jdoe", Arrays.asList(role)); address.setOwner(person);
ObjectFormatter.configureGenerator(new FormattedStringGenerator(new SimpleFormatter()));
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/examples/formatters/FormattersExample.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // }
import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*; import net.davidtanzer.jobjectformatter.formatter.*; import java.util.Arrays; import java.util.List;
package net.davidtanzer.jobjectformatter.examples.formatters; public class FormattersExample { public static void main(String[] args) { Role role = new Role("admin"); Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address, "jdoe", Arrays.asList(role)); address.setOwner(person);
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/examples/formatters/FormattersExample.java import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*; import net.davidtanzer.jobjectformatter.formatter.*; import java.util.Arrays; import java.util.List; package net.davidtanzer.jobjectformatter.examples.formatters; public class FormattersExample { public static void main(String[] args) { Role role = new Role("admin"); Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address, "jdoe", Arrays.asList(role)); address.setOwner(person);
ObjectFormatter.configureGenerator(new FormattedStringGenerator(new SimpleFormatter()));
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/examples/simple/SimpleExample.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // }
import net.davidtanzer.jobjectformatter.ObjectFormatter;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.examples.simple; public class SimpleExample { public static void main(String[] args) { Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address); System.out.println("person.toString() -> " + person); System.out.println("address.toString() -> " + address); } private static class Person { private String firstName; private String lastName; private Address address; public Person(final String firstName, final String lastName, final Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } @Override public String toString() {
// Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/examples/simple/SimpleExample.java import net.davidtanzer.jobjectformatter.ObjectFormatter; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.examples.simple; public class SimpleExample { public static void main(String[] args) { Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address); System.out.println("person.toString() -> " + person); System.out.println("address.toString() -> " + address); } private static class Person { private String firstName; private String lastName; private Address address; public Person(final String firstName, final String lastName, final Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } @Override public String toString() {
return ObjectFormatter.format(this);
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/formatter/SimpleFormatter.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ValueInfo.java // public class ValueInfo { // private final String propertyName; // private final Object value; // private final Class<?> propertyType; // // public ValueInfo(final String propertyName, final Object value, final Class<?> propertyType) { // this.propertyName = propertyName; // this.value = value; // this.propertyType = propertyType; // } // // /** // * Get the name of the property. // * // * @return the name of the property. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Get the value of the property. // * // * @return the value of the property. // */ // public Object getValue() { // return value; // } // // /** // * Get the type of the property. // * // * @return the type of the property. // */ // public Class<?> getPropertyType() { // return propertyType; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ValueInfo valueInfo = (ValueInfo) o; // // if (propertyName != null ? !propertyName.equals(valueInfo.propertyName) : valueInfo.propertyName != null) // return false; // return value != null ? value.equals(valueInfo.value) : valueInfo.value == null; // // } // // @Override // public int hashCode() { // int result = propertyName != null ? propertyName.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ValueInfo{" + // "getPropertyName='" + propertyName + '\'' + // ", getValue='" + value + '\'' + // '}'; // } // }
import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; /** * A formatter that is not configurable and has a very simple output - Used as default formatter when no other formatter is configured. * * Example output: * <pre> { firstName=Jane, lastName=Doe, address=[not null] } * </pre> */ public class SimpleFormatter extends AbstractObjectStringFormatter { public SimpleFormatter() { super(FormatGrouped.NO); } @Override
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ValueInfo.java // public class ValueInfo { // private final String propertyName; // private final Object value; // private final Class<?> propertyType; // // public ValueInfo(final String propertyName, final Object value, final Class<?> propertyType) { // this.propertyName = propertyName; // this.value = value; // this.propertyType = propertyType; // } // // /** // * Get the name of the property. // * // * @return the name of the property. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Get the value of the property. // * // * @return the value of the property. // */ // public Object getValue() { // return value; // } // // /** // * Get the type of the property. // * // * @return the type of the property. // */ // public Class<?> getPropertyType() { // return propertyType; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ValueInfo valueInfo = (ValueInfo) o; // // if (propertyName != null ? !propertyName.equals(valueInfo.propertyName) : valueInfo.propertyName != null) // return false; // return value != null ? value.equals(valueInfo.value) : valueInfo.value == null; // // } // // @Override // public int hashCode() { // int result = propertyName != null ? propertyName.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ValueInfo{" + // "getPropertyName='" + propertyName + '\'' + // ", getValue='" + value + '\'' + // '}'; // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/formatter/SimpleFormatter.java import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; /** * A formatter that is not configurable and has a very simple output - Used as default formatter when no other formatter is configured. * * Example output: * <pre> { firstName=Jane, lastName=Doe, address=[not null] } * </pre> */ public class SimpleFormatter extends AbstractObjectStringFormatter { public SimpleFormatter() { super(FormatGrouped.NO); } @Override
protected void startFormattedString(final StringBuilder result, final ObjectValuesInfo info) {
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/formatter/SimpleFormatter.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ValueInfo.java // public class ValueInfo { // private final String propertyName; // private final Object value; // private final Class<?> propertyType; // // public ValueInfo(final String propertyName, final Object value, final Class<?> propertyType) { // this.propertyName = propertyName; // this.value = value; // this.propertyType = propertyType; // } // // /** // * Get the name of the property. // * // * @return the name of the property. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Get the value of the property. // * // * @return the value of the property. // */ // public Object getValue() { // return value; // } // // /** // * Get the type of the property. // * // * @return the type of the property. // */ // public Class<?> getPropertyType() { // return propertyType; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ValueInfo valueInfo = (ValueInfo) o; // // if (propertyName != null ? !propertyName.equals(valueInfo.propertyName) : valueInfo.propertyName != null) // return false; // return value != null ? value.equals(valueInfo.value) : valueInfo.value == null; // // } // // @Override // public int hashCode() { // int result = propertyName != null ? propertyName.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ValueInfo{" + // "getPropertyName='" + propertyName + '\'' + // ", getValue='" + value + '\'' + // '}'; // } // }
import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; /** * A formatter that is not configurable and has a very simple output - Used as default formatter when no other formatter is configured. * * Example output: * <pre> { firstName=Jane, lastName=Doe, address=[not null] } * </pre> */ public class SimpleFormatter extends AbstractObjectStringFormatter { public SimpleFormatter() { super(FormatGrouped.NO); } @Override protected void startFormattedString(final StringBuilder result, final ObjectValuesInfo info) { result.append("{ "); } @Override protected void endFormattedString(final StringBuilder result, final ObjectValuesInfo info) { result.append(" }"); } @Override
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ValueInfo.java // public class ValueInfo { // private final String propertyName; // private final Object value; // private final Class<?> propertyType; // // public ValueInfo(final String propertyName, final Object value, final Class<?> propertyType) { // this.propertyName = propertyName; // this.value = value; // this.propertyType = propertyType; // } // // /** // * Get the name of the property. // * // * @return the name of the property. // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Get the value of the property. // * // * @return the value of the property. // */ // public Object getValue() { // return value; // } // // /** // * Get the type of the property. // * // * @return the type of the property. // */ // public Class<?> getPropertyType() { // return propertyType; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ValueInfo valueInfo = (ValueInfo) o; // // if (propertyName != null ? !propertyName.equals(valueInfo.propertyName) : valueInfo.propertyName != null) // return false; // return value != null ? value.equals(valueInfo.value) : valueInfo.value == null; // // } // // @Override // public int hashCode() { // int result = propertyName != null ? propertyName.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ValueInfo{" + // "getPropertyName='" + propertyName + '\'' + // ", getValue='" + value + '\'' + // '}'; // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/formatter/SimpleFormatter.java import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; /** * A formatter that is not configurable and has a very simple output - Used as default formatter when no other formatter is configured. * * Example output: * <pre> { firstName=Jane, lastName=Doe, address=[not null] } * </pre> */ public class SimpleFormatter extends AbstractObjectStringFormatter { public SimpleFormatter() { super(FormatGrouped.NO); } @Override protected void startFormattedString(final StringBuilder result, final ObjectValuesInfo info) { result.append("{ "); } @Override protected void endFormattedString(final StringBuilder result, final ObjectValuesInfo info) { result.append(" }"); } @Override
protected void appendSingleValue(final StringBuilder result, final ValueInfo value) {
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfo.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedInclude.java // public enum FormattedInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // }, // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTATED_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // if (propertyInfo.getIncludeField().equals(FormattedFieldType.DEFAULT)) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // } // }, // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // } // }; // // /** // * Implements the behavior how the field value should be added based on the value of this enum. // * // * @param builder The {@link net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo.Builder} where the caller collects the values. // * @param propertyInfo The {@link PropertyInfo} of the current filed. // * @param formattedFieldValue The value of the field in the current object (already formatted). // */ // public abstract void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue); // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // }
import net.davidtanzer.jobjectformatter.annotations.FormattedInclude; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a class that can be formatted as string. */ public class TypeInfo { private final List<ClassInfo> classInfos;
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedInclude.java // public enum FormattedInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // }, // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTATED_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // if (propertyInfo.getIncludeField().equals(FormattedFieldType.DEFAULT)) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // } // }, // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // } // }; // // /** // * Implements the behavior how the field value should be added based on the value of this enum. // * // * @param builder The {@link net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo.Builder} where the caller collects the values. // * @param propertyInfo The {@link PropertyInfo} of the current filed. // * @param formattedFieldValue The value of the field in the current object (already formatted). // */ // public abstract void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue); // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // } // Path: src/main/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfo.java import net.davidtanzer.jobjectformatter.annotations.FormattedInclude; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a class that can be formatted as string. */ public class TypeInfo { private final List<ClassInfo> classInfos;
private final TransitiveInclude transitiveInclude;
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfo.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedInclude.java // public enum FormattedInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // }, // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTATED_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // if (propertyInfo.getIncludeField().equals(FormattedFieldType.DEFAULT)) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // } // }, // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // } // }; // // /** // * Implements the behavior how the field value should be added based on the value of this enum. // * // * @param builder The {@link net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo.Builder} where the caller collects the values. // * @param propertyInfo The {@link PropertyInfo} of the current filed. // * @param formattedFieldValue The value of the field in the current object (already formatted). // */ // public abstract void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue); // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // }
import net.davidtanzer.jobjectformatter.annotations.FormattedInclude; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a class that can be formatted as string. */ public class TypeInfo { private final List<ClassInfo> classInfos; private final TransitiveInclude transitiveInclude;
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedInclude.java // public enum FormattedInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // }, // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTATED_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // if (propertyInfo.getIncludeField().equals(FormattedFieldType.DEFAULT)) { // builder.addFieldValue(propertyInfo.getName(), formattedFieldValue, propertyInfo.getType()); // } // } // }, // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue) { // } // }; // // /** // * Implements the behavior how the field value should be added based on the value of this enum. // * // * @param builder The {@link net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo.Builder} where the caller collects the values. // * @param propertyInfo The {@link PropertyInfo} of the current filed. // * @param formattedFieldValue The value of the field in the current object (already formatted). // */ // public abstract void addFieldValueTo(final GroupedValuesInfo.Builder builder, final PropertyInfo propertyInfo, final Object formattedFieldValue); // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // } // Path: src/main/java/net/davidtanzer/jobjectformatter/typeinfo/TypeInfo.java import net.davidtanzer.jobjectformatter.annotations.FormattedInclude; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a class that can be formatted as string. */ public class TypeInfo { private final List<ClassInfo> classInfos; private final TransitiveInclude transitiveInclude;
private final FormattedInclude formattedInclude;
dtanzer/jobjectformatter
src/test/java/net/davidtanzer/jobjectformatter/formatter/ConfigurableObjectStringFormatterTest.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // }
import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package net.davidtanzer.jobjectformatter.formatter; public class ConfigurableObjectStringFormatterTest { @Test public void ungroupedCurlyBracedOutputWithClassNameTest() { final ConfigurableObjectStringFormatter formatter = ConfigurableObjectStringFormatter.UNGROUPED_CURLY_BRACED_OUTPUT_WITH_CLASS_NAME;
// Path: src/main/java/net/davidtanzer/jobjectformatter/FormattedStringGenerator.java // public class FormattedStringGenerator { // private final TypeInfoCache typeInfoCache; // private final ObjectValuesCompiler objectValuesCompiler; // private final ObjectStringFormatter toStringFormatter; // // /** // * Creates a new FormattedStringGenerator that uses a {@link net.davidtanzer.jobjectformatter.formatter.SimpleFormatter} to format the string. // * // * @see net.davidtanzer.jobjectformatter.formatter.SimpleFormatter // */ // public FormattedStringGenerator() { // this(new SimpleFormatter(), new TypeInfoCache(), new ObjectValuesCompiler()); // } // // /** // * Creates a new FormattedStringGenerator with a given {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter}. // * // * @param toStringFormatter The formatter to use when creating formatted strings. // * @see net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter // */ // public FormattedStringGenerator(final ObjectStringFormatter toStringFormatter) { // this(toStringFormatter, new TypeInfoCache(), new ObjectValuesCompiler()); // } // // FormattedStringGenerator(final ObjectStringFormatter objectStringFormatter, final TypeInfoCache typeInfoCache, final ObjectValuesCompiler objectValuesCompiler) { // if(objectStringFormatter == null) { // throw new IllegalArgumentException("Parameter objectStringFormatter must not be null!"); // } // assert typeInfoCache != null : "Parameter typeInfoCache must not be null!"; // assert objectValuesCompiler != null : "Parameter objectValuesCompiler must not be null!"; // // this.toStringFormatter = objectStringFormatter; // this.typeInfoCache = typeInfoCache; // this.objectValuesCompiler = objectValuesCompiler; // } // // /** // * Creates a formatted String representation of an object. // * // * @param object The object to format. // * @return The formatted String representation. // */ // public String format(final Object object) { // if(object==null) { // throw new IllegalArgumentException("Parameter object must not be null!"); // } // // final TypeInfo typeInfo = typeInfoCache.typeInfoFor(object.getClass()); // final ObjectValuesInfo objectValuesInfo = objectValuesCompiler.compileToStringInfo(typeInfo, object); // // return toStringFormatter.format(objectValuesInfo); // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // Path: src/test/java/net/davidtanzer/jobjectformatter/formatter/ConfigurableObjectStringFormatterTest.java import net.davidtanzer.jobjectformatter.FormattedStringGenerator; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package net.davidtanzer.jobjectformatter.formatter; public class ConfigurableObjectStringFormatterTest { @Test public void ungroupedCurlyBracedOutputWithClassNameTest() { final ConfigurableObjectStringFormatter formatter = ConfigurableObjectStringFormatter.UNGROUPED_CURLY_BRACED_OUTPUT_WITH_CLASS_NAME;
FormattedStringGenerator generator = new FormattedStringGenerator(formatter);
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/typeinfo/PropertyInfo.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedFieldType.java // public enum FormattedFieldType { // /** // * Include the field in the formatted output. // */ // DEFAULT, // /** // * Include the field in the formatted output, but only when the output is set to "verbose". // */ // VERBOSE, // /** // * Do not include the field in the formatted output. // */ // NEVER // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // }
import net.davidtanzer.jobjectformatter.annotations.FormattedFieldType; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.lang.reflect.Field;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a property of an object. */ public class PropertyInfo { private final Field field;
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedFieldType.java // public enum FormattedFieldType { // /** // * Include the field in the formatted output. // */ // DEFAULT, // /** // * Include the field in the formatted output, but only when the output is set to "verbose". // */ // VERBOSE, // /** // * Do not include the field in the formatted output. // */ // NEVER // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // } // Path: src/main/java/net/davidtanzer/jobjectformatter/typeinfo/PropertyInfo.java import net.davidtanzer.jobjectformatter.annotations.FormattedFieldType; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.lang.reflect.Field; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a property of an object. */ public class PropertyInfo { private final Field field;
private final TransitiveInclude transitiveIncludeOfTarget;
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/typeinfo/PropertyInfo.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedFieldType.java // public enum FormattedFieldType { // /** // * Include the field in the formatted output. // */ // DEFAULT, // /** // * Include the field in the formatted output, but only when the output is set to "verbose". // */ // VERBOSE, // /** // * Do not include the field in the formatted output. // */ // NEVER // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // }
import net.davidtanzer.jobjectformatter.annotations.FormattedFieldType; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.lang.reflect.Field;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a property of an object. */ public class PropertyInfo { private final Field field; private final TransitiveInclude transitiveIncludeOfTarget;
// Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/FormattedFieldType.java // public enum FormattedFieldType { // /** // * Include the field in the formatted output. // */ // DEFAULT, // /** // * Include the field in the formatted output, but only when the output is set to "verbose". // */ // VERBOSE, // /** // * Do not include the field in the formatted output. // */ // NEVER // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java // public enum TransitiveInclude { // /** // * Include all fields in the formatted output. // */ // ALL_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // return fieldValue; // } // }, // // /** // * Include only fields in the formatted output where the field has the {@link net.davidtanzer.jobjectformatter.annotations.FormattedField} // * annotation and is configured to be included. // * // * @see net.davidtanzer.jobjectformatter.annotations.FormattedField // * @see net.davidtanzer.jobjectformatter.annotations.FormattedFieldType // */ // ANNOTADED_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(hasFormattedAnnotation) { // if(transitiveValues.getAllValues().isEmpty()) { // return "[not null]"; // } else { // return transitiveValues; // } // } else { // return fieldValue; // } // } // }, // // /** // * Do not include any fields in the formatted output. // */ // NO_FIELDS { // @Override // public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) { // if(fieldValue == null) { // return null; // } else { // return "[not null]"; // } // } // }; // // /** // * Get the transitive field value (already formatted) of the field based on the value of this enum. // * // * @param fieldValue The value of the current field. // * @param hasFormattedAnnotation true when the field or the referenced class has the formatted annotation. // * @param transitiveValues An {@link net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo} that contains all relevant values from the transitive object. // * @return The formatted field value that will be passed to the {@link net.davidtanzer.jobjectformatter.formatter.ObjectStringFormatter} // */ // public abstract Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues); // } // Path: src/main/java/net/davidtanzer/jobjectformatter/typeinfo/PropertyInfo.java import net.davidtanzer.jobjectformatter.annotations.FormattedFieldType; import net.davidtanzer.jobjectformatter.annotations.TransitiveInclude; import java.lang.reflect.Field; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.typeinfo; /** * Type information about a property of an object. */ public class PropertyInfo { private final Field field; private final TransitiveInclude transitiveIncludeOfTarget;
private final FormattedFieldType includeFieldInTransitive;
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // }
import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.annotations; /** * With TransitiveInclude, you can configure which types of fields (all, annotated or none) to include in the formatted output * using the {@link net.davidtanzer.jobjectformatter.annotations.Formatted} annotation. * * @see net.davidtanzer.jobjectformatter.annotations.Formatted */ public enum TransitiveInclude { /** * Include all fields in the formatted output. */ ALL_FIELDS { @Override
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/annotations/TransitiveInclude.java import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.annotations; /** * With TransitiveInclude, you can configure which types of fields (all, annotated or none) to include in the formatted output * using the {@link net.davidtanzer.jobjectformatter.annotations.Formatted} annotation. * * @see net.davidtanzer.jobjectformatter.annotations.Formatted */ public enum TransitiveInclude { /** * Include all fields in the formatted output. */ ALL_FIELDS { @Override
public Object transitiveFieldValue(final Object fieldValue, final boolean hasFormattedAnnotation, final ObjectValuesInfo transitiveValues) {
dtanzer/jobjectformatter
src/main/java/net/davidtanzer/jobjectformatter/examples/annotated/AnnotationsExample.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // }
import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.examples.annotated; public class AnnotationsExample { public static void main(String[] args) { Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address); address.setOwner(person); System.out.println("Person: " + person); System.out.println("Address: " + address); System.out.println("Person (only annotated fields): " + new PersonAnnotatedFields("Jane", "Doe", address)); System.out.println("Person (no): " + new PersonNoFields("Jane", "Doe", address)); } private static class Person { private String firstName; @FormattedField(transitive = FormattedFieldType.DEFAULT) private String lastName; private Address address; public Person(final String firstName, final String lastName, final Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } @Override @Formatted(value = FormattedInclude.ALL_FIELDS, transitive = TransitiveInclude.NO_FIELDS) public String toString() {
// Path: src/main/java/net/davidtanzer/jobjectformatter/ObjectFormatter.java // public class ObjectFormatter { // private static AtomicReference<FormattedStringGenerator> generator = new AtomicReference<>(new FormattedStringGenerator()); // // /** // * Configure the {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator} to use when formatting objects. // * // * @param generator The globally configured generator. // */ // public static void configureGenerator(final FormattedStringGenerator generator) { // ObjectFormatter.generator.set(generator); // } // // /** // * Format an object with the globally configured {@link net.davidtanzer.jobjectformatter.FormattedStringGenerator}. // * // * @param object The object to format. // * @return The string representation of the object. // */ // public static String format(final Object object) { // return generator.get().format(object); // } // } // Path: src/main/java/net/davidtanzer/jobjectformatter/examples/annotated/AnnotationsExample.java import net.davidtanzer.jobjectformatter.ObjectFormatter; import net.davidtanzer.jobjectformatter.annotations.*; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.examples.annotated; public class AnnotationsExample { public static void main(String[] args) { Address address = new Address("Evergreen Terrace", "12b"); Person person = new Person("Jane", "Doe", address); address.setOwner(person); System.out.println("Person: " + person); System.out.println("Address: " + address); System.out.println("Person (only annotated fields): " + new PersonAnnotatedFields("Jane", "Doe", address)); System.out.println("Person (no): " + new PersonNoFields("Jane", "Doe", address)); } private static class Person { private String firstName; @FormattedField(transitive = FormattedFieldType.DEFAULT) private String lastName; private Address address; public Person(final String firstName, final String lastName, final Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } @Override @Formatted(value = FormattedInclude.ALL_FIELDS, transitive = TransitiveInclude.NO_FIELDS) public String toString() {
return ObjectFormatter.format(this);
dtanzer/jobjectformatter
src/test/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatterTest.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/GroupedValuesInfo.java // public class GroupedValuesInfo { // private final String groupName; // private final List<ValueInfo> values; // // private GroupedValuesInfo(final String groupName, final List<ValueInfo> values) { // this.groupName = groupName; // this.values = values; // } // // /** // * Get the name of the group. // * // * @return the name of the group. // */ // public String getGroupName() { // return groupName; // } // // /** // * Get all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // * // * @return all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // */ // public List<ValueInfo> getValues() { // return values; // } // // /** // * A builder to create GroupedValuesInfo objects. // */ // public static class Builder { // private String groupName; // private final List<ValueInfo> values = new ArrayList<>(); // // /** // * Build the grouped values info from the information provided before calling this method. // * // * <strong>Do not use the builder after calling this method!</strong> // * // * @return The newly created GroupedValuesInfo. // */ // public GroupedValuesInfo buildGroupedValuesInfo() { // return new GroupedValuesInfo(groupName, Collections.unmodifiableList(values)); // } // // /** // * Set the class name for the grouped values info. // * // * @param className the class name for the grouped values info. // * @return the builder itself. // */ // public Builder setClassName(final String className) { // this.groupName = className; // return this; // } // // /** // * Add a field value to the grouped values info. // * @param name the name of the field. // * @param formattedFieldValue the formatted value of the field. // * @param fieldClass The class of the field. // * @return the builder itself. // */ // public Builder addFieldValue(final String name, final Object formattedFieldValue, final Class<?> fieldClass) { // values.add(new ValueInfo(name, formattedFieldValue, fieldClass)); // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // }
import net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; public class JsonObjectStringFormatterTest { @Before public void setup() throws Exception { } @Test public void formatsGroupedByClassesCorrectly() { final JsonObjectStringFormatter formatter = new JsonObjectStringFormatter();
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/GroupedValuesInfo.java // public class GroupedValuesInfo { // private final String groupName; // private final List<ValueInfo> values; // // private GroupedValuesInfo(final String groupName, final List<ValueInfo> values) { // this.groupName = groupName; // this.values = values; // } // // /** // * Get the name of the group. // * // * @return the name of the group. // */ // public String getGroupName() { // return groupName; // } // // /** // * Get all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // * // * @return all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // */ // public List<ValueInfo> getValues() { // return values; // } // // /** // * A builder to create GroupedValuesInfo objects. // */ // public static class Builder { // private String groupName; // private final List<ValueInfo> values = new ArrayList<>(); // // /** // * Build the grouped values info from the information provided before calling this method. // * // * <strong>Do not use the builder after calling this method!</strong> // * // * @return The newly created GroupedValuesInfo. // */ // public GroupedValuesInfo buildGroupedValuesInfo() { // return new GroupedValuesInfo(groupName, Collections.unmodifiableList(values)); // } // // /** // * Set the class name for the grouped values info. // * // * @param className the class name for the grouped values info. // * @return the builder itself. // */ // public Builder setClassName(final String className) { // this.groupName = className; // return this; // } // // /** // * Add a field value to the grouped values info. // * @param name the name of the field. // * @param formattedFieldValue the formatted value of the field. // * @param fieldClass The class of the field. // * @return the builder itself. // */ // public Builder addFieldValue(final String name, final Object formattedFieldValue, final Class<?> fieldClass) { // values.add(new ValueInfo(name, formattedFieldValue, fieldClass)); // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // Path: src/test/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatterTest.java import net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; public class JsonObjectStringFormatterTest { @Before public void setup() throws Exception { } @Test public void formatsGroupedByClassesCorrectly() { final JsonObjectStringFormatter formatter = new JsonObjectStringFormatter();
final GroupedValuesInfo classInfo = new GroupedValuesInfo.Builder()
dtanzer/jobjectformatter
src/test/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatterTest.java
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/GroupedValuesInfo.java // public class GroupedValuesInfo { // private final String groupName; // private final List<ValueInfo> values; // // private GroupedValuesInfo(final String groupName, final List<ValueInfo> values) { // this.groupName = groupName; // this.values = values; // } // // /** // * Get the name of the group. // * // * @return the name of the group. // */ // public String getGroupName() { // return groupName; // } // // /** // * Get all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // * // * @return all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // */ // public List<ValueInfo> getValues() { // return values; // } // // /** // * A builder to create GroupedValuesInfo objects. // */ // public static class Builder { // private String groupName; // private final List<ValueInfo> values = new ArrayList<>(); // // /** // * Build the grouped values info from the information provided before calling this method. // * // * <strong>Do not use the builder after calling this method!</strong> // * // * @return The newly created GroupedValuesInfo. // */ // public GroupedValuesInfo buildGroupedValuesInfo() { // return new GroupedValuesInfo(groupName, Collections.unmodifiableList(values)); // } // // /** // * Set the class name for the grouped values info. // * // * @param className the class name for the grouped values info. // * @return the builder itself. // */ // public Builder setClassName(final String className) { // this.groupName = className; // return this; // } // // /** // * Add a field value to the grouped values info. // * @param name the name of the field. // * @param formattedFieldValue the formatted value of the field. // * @param fieldClass The class of the field. // * @return the builder itself. // */ // public Builder addFieldValue(final String name, final Object formattedFieldValue, final Class<?> fieldClass) { // values.add(new ValueInfo(name, formattedFieldValue, fieldClass)); // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // }
import net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; public class JsonObjectStringFormatterTest { @Before public void setup() throws Exception { } @Test public void formatsGroupedByClassesCorrectly() { final JsonObjectStringFormatter formatter = new JsonObjectStringFormatter(); final GroupedValuesInfo classInfo = new GroupedValuesInfo.Builder() .setClassName("Foo") .addFieldValue("foo", "foobar", String.class) .addFieldValue("bar", "123", Integer.class) .buildGroupedValuesInfo();
// Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/GroupedValuesInfo.java // public class GroupedValuesInfo { // private final String groupName; // private final List<ValueInfo> values; // // private GroupedValuesInfo(final String groupName, final List<ValueInfo> values) { // this.groupName = groupName; // this.values = values; // } // // /** // * Get the name of the group. // * // * @return the name of the group. // */ // public String getGroupName() { // return groupName; // } // // /** // * Get all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // * // * @return all values of the group as {@link net.davidtanzer.jobjectformatter.valuesinfo.ValueInfo}. // */ // public List<ValueInfo> getValues() { // return values; // } // // /** // * A builder to create GroupedValuesInfo objects. // */ // public static class Builder { // private String groupName; // private final List<ValueInfo> values = new ArrayList<>(); // // /** // * Build the grouped values info from the information provided before calling this method. // * // * <strong>Do not use the builder after calling this method!</strong> // * // * @return The newly created GroupedValuesInfo. // */ // public GroupedValuesInfo buildGroupedValuesInfo() { // return new GroupedValuesInfo(groupName, Collections.unmodifiableList(values)); // } // // /** // * Set the class name for the grouped values info. // * // * @param className the class name for the grouped values info. // * @return the builder itself. // */ // public Builder setClassName(final String className) { // this.groupName = className; // return this; // } // // /** // * Add a field value to the grouped values info. // * @param name the name of the field. // * @param formattedFieldValue the formatted value of the field. // * @param fieldClass The class of the field. // * @return the builder itself. // */ // public Builder addFieldValue(final String name, final Object formattedFieldValue, final Class<?> fieldClass) { // values.add(new ValueInfo(name, formattedFieldValue, fieldClass)); // return this; // } // } // } // // Path: src/main/java/net/davidtanzer/jobjectformatter/valuesinfo/ObjectValuesInfo.java // public class ObjectValuesInfo { // private final List<GroupedValuesInfo> valuesByClass; // private final List<ValueInfo> allValues; // private final Class type; // // private ObjectValuesInfo(final List<GroupedValuesInfo> valuesByClass, final List<ValueInfo> allValues, final Class type) { // this.valuesByClass = valuesByClass; // this.allValues = allValues; // this.type = type; // } // // /** // * Get all values of the object's properties, grouped by their declaring class. // * // * @return all values of the object's properties, grouped by their declaring class. // */ // public List<GroupedValuesInfo> getValuesByClass() { // return valuesByClass; // } // // /** // * Get all values of the object's properties. // * // * @return all values of the object's properties. // */ // public List<ValueInfo> getAllValues() { // return allValues; // } // // /** // * Get the type of the object to format. // * // * @return the type of the object to format. // */ // public Class getType() { // return type; // } // // static class Builder { // private final List<GroupedValuesInfo> valuesByClass = new ArrayList<>(); // private final List<ValueInfo> allValues = new ArrayList<>(); // private Class type; // // public ObjectValuesInfo buildToStringInfo() { // return new ObjectValuesInfo( // Collections.unmodifiableList(valuesByClass), // Collections.unmodifiableList(allValues), // type); // } // // Builder addClassValues(final GroupedValuesInfo groupedValuesInfo) { // valuesByClass.add(groupedValuesInfo); // allValues.addAll(groupedValuesInfo.getValues()); // return this; // } // // Builder setType(Class type) { // this.type = type; // return this; // } // } // } // Path: src/test/java/net/davidtanzer/jobjectformatter/formatter/JsonObjectStringFormatterTest.java import net.davidtanzer.jobjectformatter.valuesinfo.GroupedValuesInfo; import net.davidtanzer.jobjectformatter.valuesinfo.ObjectValuesInfo; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* Copyright 2015 David Tanzer (business@davidtanzer.net / @dtanzer) 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 net.davidtanzer.jobjectformatter.formatter; public class JsonObjectStringFormatterTest { @Before public void setup() throws Exception { } @Test public void formatsGroupedByClassesCorrectly() { final JsonObjectStringFormatter formatter = new JsonObjectStringFormatter(); final GroupedValuesInfo classInfo = new GroupedValuesInfo.Builder() .setClassName("Foo") .addFieldValue("foo", "foobar", String.class) .addFieldValue("bar", "123", Integer.class) .buildGroupedValuesInfo();
final ObjectValuesInfo info = mock(ObjectValuesInfo.class);
timothyb89/lifx-java
src/main/java/org/timothyb89/lifx/bulb/LIFXColor.java
// Path: src/main/java/org/timothyb89/lifx/net/packet/response/LightStatusResponse.java // @ToString(callSuper = true) // public class LightStatusResponse extends Packet { // // public static final int TYPE = 0x6B; // // public static final Field<Integer> FIELD_HUE = new UInt16Field().little(); // public static final Field<Integer> FIELD_SATURATION = new UInt16Field().little(); // public static final Field<Integer> FIELD_BRIGHTNESS = new UInt16Field().little(); // public static final Field<Integer> FIELD_KELVIN = new UInt16Field().little(); // public static final Field<Integer> FIELD_DIM = new UInt16Field().little(); // public static final Field<Integer> FIELD_POWER = new UInt16Field(); // public static final Field<String> FIELD_LABEL = new StringField(32); // public static final Field<Long> FIELD_TAGS = new UInt64Field(); // // @Getter private int hue; // @Getter private int saturation; // @Getter private int brightness; // @Getter private int kelvin; // @Getter private int dim; // @Getter private PowerState power; // PowerState? // @Getter private String label; // @Getter private long tags; // // @Override // public int packetType() { // return TYPE; // } // // @Override // protected int packetLength() { // return 52; // } // // @Override // protected void parsePacket(ByteBuffer bytes) { // hue = FIELD_HUE .value(bytes); // saturation = FIELD_SATURATION.value(bytes); // brightness = FIELD_BRIGHTNESS.value(bytes); // kelvin = FIELD_KELVIN .value(bytes); // dim = FIELD_DIM .value(bytes); // power = PowerState.fromValue(FIELD_POWER.value(bytes)); // label = FIELD_LABEL .value(bytes); // tags = FIELD_TAGS .value(bytes); // } // // @Override // protected ByteBuffer packetBytes() { // return ByteBuffer.allocate(packetLength()) // .put(FIELD_HUE.bytes(hue)) // .put(FIELD_SATURATION.bytes(saturation)) // .put(FIELD_BRIGHTNESS.bytes(brightness)) // .put(FIELD_KELVIN.bytes(kelvin)) // .put(FIELD_DIM.bytes(dim)) // .put(FIELD_POWER.bytes(hue)) // .put(FIELD_LABEL.bytes(label)) // .put(FIELD_TAGS.bytes(tags)); // } // // @Override // public int[] expectedResponses() { // return new int[] {}; // } // // }
import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.timothyb89.lifx.net.packet.response.LightStatusResponse;
package org.timothyb89.lifx.bulb; /** * A basic implementation of a color in the HSVK space, compatible with LIFX * bulbs. This implementation uses colors ranging from {@link #MIN_VALUE} * (0x0000) to {@link #MAX_VALUE} (0xFFFF) * @author tim */ @ToString @EqualsAndHashCode public class LIFXColor { public static final int MIN_VALUE = 0x0000; public static final int MAX_VALUE = 0xFFFF; public static final int DEFAULT_KELVIN = 3500; @Getter private int hue; @Getter private int saturation; @Getter private int value; @Getter private int kelvin; /** * Creates a new LIFXColor with unspecified values. */ public LIFXColor() { } /** * Creates a new LIFXColor using values from the given light status packet. * @param packet the packet to copy values from */
// Path: src/main/java/org/timothyb89/lifx/net/packet/response/LightStatusResponse.java // @ToString(callSuper = true) // public class LightStatusResponse extends Packet { // // public static final int TYPE = 0x6B; // // public static final Field<Integer> FIELD_HUE = new UInt16Field().little(); // public static final Field<Integer> FIELD_SATURATION = new UInt16Field().little(); // public static final Field<Integer> FIELD_BRIGHTNESS = new UInt16Field().little(); // public static final Field<Integer> FIELD_KELVIN = new UInt16Field().little(); // public static final Field<Integer> FIELD_DIM = new UInt16Field().little(); // public static final Field<Integer> FIELD_POWER = new UInt16Field(); // public static final Field<String> FIELD_LABEL = new StringField(32); // public static final Field<Long> FIELD_TAGS = new UInt64Field(); // // @Getter private int hue; // @Getter private int saturation; // @Getter private int brightness; // @Getter private int kelvin; // @Getter private int dim; // @Getter private PowerState power; // PowerState? // @Getter private String label; // @Getter private long tags; // // @Override // public int packetType() { // return TYPE; // } // // @Override // protected int packetLength() { // return 52; // } // // @Override // protected void parsePacket(ByteBuffer bytes) { // hue = FIELD_HUE .value(bytes); // saturation = FIELD_SATURATION.value(bytes); // brightness = FIELD_BRIGHTNESS.value(bytes); // kelvin = FIELD_KELVIN .value(bytes); // dim = FIELD_DIM .value(bytes); // power = PowerState.fromValue(FIELD_POWER.value(bytes)); // label = FIELD_LABEL .value(bytes); // tags = FIELD_TAGS .value(bytes); // } // // @Override // protected ByteBuffer packetBytes() { // return ByteBuffer.allocate(packetLength()) // .put(FIELD_HUE.bytes(hue)) // .put(FIELD_SATURATION.bytes(saturation)) // .put(FIELD_BRIGHTNESS.bytes(brightness)) // .put(FIELD_KELVIN.bytes(kelvin)) // .put(FIELD_DIM.bytes(dim)) // .put(FIELD_POWER.bytes(hue)) // .put(FIELD_LABEL.bytes(label)) // .put(FIELD_TAGS.bytes(tags)); // } // // @Override // public int[] expectedResponses() { // return new int[] {}; // } // // } // Path: src/main/java/org/timothyb89/lifx/bulb/LIFXColor.java import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.timothyb89.lifx.net.packet.response.LightStatusResponse; package org.timothyb89.lifx.bulb; /** * A basic implementation of a color in the HSVK space, compatible with LIFX * bulbs. This implementation uses colors ranging from {@link #MIN_VALUE} * (0x0000) to {@link #MAX_VALUE} (0xFFFF) * @author tim */ @ToString @EqualsAndHashCode public class LIFXColor { public static final int MIN_VALUE = 0x0000; public static final int MAX_VALUE = 0xFFFF; public static final int DEFAULT_KELVIN = 3500; @Getter private int hue; @Getter private int saturation; @Getter private int value; @Getter private int kelvin; /** * Creates a new LIFXColor with unspecified values. */ public LIFXColor() { } /** * Creates a new LIFXColor using values from the given light status packet. * @param packet the packet to copy values from */
public LIFXColor(LightStatusResponse packet) {
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLDesignerStandalone.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/io/FileDocumentIO.java // public class FileDocumentIO implements DocumentIO { // static { // RDFFormat.register(RDFFormat.RDFXML); // } // // // private final SBOLReader reader; // // private final SBOLWriter writer; // // public FileDocumentIO(boolean validate) { // File file = SBOLUtils.setupFile(); // String fileName = file.getName(); // RDFFormat format = fileName.endsWith(".xml") ? RDFFormat.RDFXML // : RDFFormat.forFileName(fileName, RDFFormat.RDFXML); // // reader = SublimeSBOLFactory.createReader(format, validate); // // writer = SublimeSBOLFactory.createWriter(format, validate); // } // // @Override // public SBOLDocument read() // throws SBOLValidationException, FileNotFoundException, IOException, SBOLConversionException { // // return reader.read(new FileInputStream(file)); // File file = SBOLUtils.setupFile(); // SBOLReader.setURIPrefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString()); // SBOLReader.setCompliant(true); // FileInputStream stream = new FileInputStream(file); // SBOLDocument doc = SBOLReader.read(stream); // stream.close(); // Preferences.userRoot().node("path").put("path", file.getPath()); // doc.setDefaultURIprefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString()); // return doc; // } // // @Override // public void write(SBOLDocument doc) throws SBOLValidationException, SBOLConversionException, IOException { // // writer.write(doc, new FileOutputStream(file)); // File file = SBOLUtils.setupFile(); // String fileName = file.getName(); // if (!fileName.contains(".")) { // file = new File(file + ".xml"); // Preferences.userRoot().node("path").put("path", file.getPath()); // } // SBOLWriter.write(doc, new FileOutputStream(file)); // } // // @Override // public String toString() { // File file = SBOLUtils.setupFile(); // return file.getName(); // } // // }
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.imageio.ImageIO; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.swing.JFrame; import javax.swing.UIManager; import org.sbolstandard.core2.SBOLValidationException; import edu.utah.ece.async.sboldesigner.sbol.editor.io.FileDocumentIO;
setSize(1280, 720); setIconImage(ImageIO.read(getClass().getResourceAsStream("/images/icon.png"))); // set behavior for close operation setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { if (panel.confirmSave()) { System.exit(0); } } catch (Exception e1) { e1.printStackTrace(); } } }); } public static void main(String[] args) throws SBOLValidationException, IOException { setup(); final SBOLDesignerStandalone frame = new SBOLDesignerStandalone(); frame.setVisible(true); frame.setLocationRelativeTo(null); if (args.length > 0) { try { File file = new File(args[0]); Preferences.userRoot().node("path").put("path", file.getPath());
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/io/FileDocumentIO.java // public class FileDocumentIO implements DocumentIO { // static { // RDFFormat.register(RDFFormat.RDFXML); // } // // // private final SBOLReader reader; // // private final SBOLWriter writer; // // public FileDocumentIO(boolean validate) { // File file = SBOLUtils.setupFile(); // String fileName = file.getName(); // RDFFormat format = fileName.endsWith(".xml") ? RDFFormat.RDFXML // : RDFFormat.forFileName(fileName, RDFFormat.RDFXML); // // reader = SublimeSBOLFactory.createReader(format, validate); // // writer = SublimeSBOLFactory.createWriter(format, validate); // } // // @Override // public SBOLDocument read() // throws SBOLValidationException, FileNotFoundException, IOException, SBOLConversionException { // // return reader.read(new FileInputStream(file)); // File file = SBOLUtils.setupFile(); // SBOLReader.setURIPrefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString()); // SBOLReader.setCompliant(true); // FileInputStream stream = new FileInputStream(file); // SBOLDocument doc = SBOLReader.read(stream); // stream.close(); // Preferences.userRoot().node("path").put("path", file.getPath()); // doc.setDefaultURIprefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString()); // return doc; // } // // @Override // public void write(SBOLDocument doc) throws SBOLValidationException, SBOLConversionException, IOException { // // writer.write(doc, new FileOutputStream(file)); // File file = SBOLUtils.setupFile(); // String fileName = file.getName(); // if (!fileName.contains(".")) { // file = new File(file + ".xml"); // Preferences.userRoot().node("path").put("path", file.getPath()); // } // SBOLWriter.write(doc, new FileOutputStream(file)); // } // // @Override // public String toString() { // File file = SBOLUtils.setupFile(); // return file.getName(); // } // // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLDesignerStandalone.java import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.imageio.ImageIO; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.swing.JFrame; import javax.swing.UIManager; import org.sbolstandard.core2.SBOLValidationException; import edu.utah.ece.async.sboldesigner.sbol.editor.io.FileDocumentIO; setSize(1280, 720); setIconImage(ImageIO.read(getClass().getResourceAsStream("/images/icon.png"))); // set behavior for close operation setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { if (panel.confirmSave()) { System.exit(0); } } catch (Exception e1) { e1.printStackTrace(); } } }); } public static void main(String[] args) throws SBOLValidationException, IOException { setup(); final SBOLDesignerStandalone frame = new SBOLDesignerStandalone(); frame.setVisible(true); frame.setLocationRelativeTo(null); if (args.length > 0) { try { File file = new File(args[0]); Preferences.userRoot().node("path").put("path", file.getPath());
frame.panel.openDocument(new FileDocumentIO(false));
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/SynBioHubQuery.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/RegistryInputDialog.java // public class TableUpdater { // public void updateTable(ArrayList<TableMetadata> identified, String filterText) { // if (!filterSelection.getText().equals(filterText)) { // // don't update if the filterSelection text has changed. // return; // } // // TableMetadataTableModel tableModel = new TableMetadataTableModel(identified); // table = new JTable(tableModel); // tableLabel.setText("Matching parts (" + identified.size() + ")"); // // refreshSearch = identified.size() >= SynBioHubQuery.QUERY_LIMIT; // if (filterText != null && !refreshSearch) { // cacheKey = filterText; // } // /* // * System.out.println(); System.out.println("TableUpdater"); // * System.out.println("refreshSearch: " + refreshSearch); // * System.out.println("cacheKey: " + cacheKey); System.out.println( // * "filter: " + filterSelection.getText()); // */ // // TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel); // table.setRowSorter(sorter); // setWidthAsPercentages(table, tableModel.getWidths()); // // table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { // @Override // public void valueChanged(ListSelectionEvent event) { // setSelectAllowed(table.getSelectedRow() >= 0); // } // }); // // table.addMouseListener(new MouseAdapter() { // public void mouseClicked(MouseEvent e) { // if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) { // handleTableSelection(false); // } // } // }); // // scroller.setViewportView(table); // } // }
import java.awt.Component; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.SwingWorker; import org.synbiohub.frontend.IdentifiedMetadata; import org.synbiohub.frontend.SearchCriteria; import org.synbiohub.frontend.SearchQuery; import org.synbiohub.frontend.SynBioHubException; import org.synbiohub.frontend.SynBioHubFrontend; import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.RegistryInputDialog.TableUpdater;
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog; public class SynBioHubQuery extends SwingWorker<Object, Object> { public static int QUERY_LIMIT = 10000; static SynBioHubQuery lastQuery = null; private boolean cancelled = false; SynBioHubFrontend synBioHub; Set<URI> roles; Set<URI> types; Set<URI> collections; String filterText;
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/RegistryInputDialog.java // public class TableUpdater { // public void updateTable(ArrayList<TableMetadata> identified, String filterText) { // if (!filterSelection.getText().equals(filterText)) { // // don't update if the filterSelection text has changed. // return; // } // // TableMetadataTableModel tableModel = new TableMetadataTableModel(identified); // table = new JTable(tableModel); // tableLabel.setText("Matching parts (" + identified.size() + ")"); // // refreshSearch = identified.size() >= SynBioHubQuery.QUERY_LIMIT; // if (filterText != null && !refreshSearch) { // cacheKey = filterText; // } // /* // * System.out.println(); System.out.println("TableUpdater"); // * System.out.println("refreshSearch: " + refreshSearch); // * System.out.println("cacheKey: " + cacheKey); System.out.println( // * "filter: " + filterSelection.getText()); // */ // // TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel); // table.setRowSorter(sorter); // setWidthAsPercentages(table, tableModel.getWidths()); // // table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { // @Override // public void valueChanged(ListSelectionEvent event) { // setSelectAllowed(table.getSelectedRow() >= 0); // } // }); // // table.addMouseListener(new MouseAdapter() { // public void mouseClicked(MouseEvent e) { // if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) { // handleTableSelection(false); // } // } // }); // // scroller.setViewportView(table); // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/SynBioHubQuery.java import java.awt.Component; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.SwingWorker; import org.synbiohub.frontend.IdentifiedMetadata; import org.synbiohub.frontend.SearchCriteria; import org.synbiohub.frontend.SearchQuery; import org.synbiohub.frontend.SynBioHubException; import org.synbiohub.frontend.SynBioHubFrontend; import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.RegistryInputDialog.TableUpdater; package edu.utah.ece.async.sboldesigner.sbol.editor.dialog; public class SynBioHubQuery extends SwingWorker<Object, Object> { public static int QUERY_LIMIT = 10000; static SynBioHubQuery lastQuery = null; private boolean cancelled = false; SynBioHubFrontend synBioHub; Set<URI> roles; Set<URI> types; Set<URI> collections; String filterText;
TableUpdater tableUpdater;
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/Parts.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/Part.java // public enum ImageType { // CENTERED_ON_BASELINE(4), SHORT_OVER_BASELINE(8), TALL_OVER_BASELINE(16); // // private final int cropRatio; // // ImageType(int ratio) { // this.cropRatio = ratio; // } // }
import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import org.sbolstandard.core2.Component; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.Identified; import org.sbolstandard.core2.SequenceAnnotation; import org.sbolstandard.core2.SequenceOntology; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import edu.utah.ece.async.sboldesigner.sbol.editor.Part.ImageType;
/* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.ece.async.sboldesigner.sbol.editor; public class Parts { private Parts() { } private static final Map<URI, Part> PARTS = Maps.newHashMap(); private static final List<Part> PARTS_LIST = Lists.newArrayList(); private static final List<Part> RENDERED_PARTS = Lists.newArrayList(); // unspecified part is for parts without roles that get opened public static final Part UNSPECIFIED = createPart("Unspecified", "UNS", "unspecified.png",
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/Part.java // public enum ImageType { // CENTERED_ON_BASELINE(4), SHORT_OVER_BASELINE(8), TALL_OVER_BASELINE(16); // // private final int cropRatio; // // ImageType(int ratio) { // this.cropRatio = ratio; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/Parts.java import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import org.sbolstandard.core2.Component; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.Identified; import org.sbolstandard.core2.SequenceAnnotation; import org.sbolstandard.core2.SequenceOntology; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import edu.utah.ece.async.sboldesigner.sbol.editor.Part.ImageType; /* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.ece.async.sboldesigner.sbol.editor; public class Parts { private Parts() { } private static final Map<URI, Part> PARTS = Maps.newHashMap(); private static final List<Part> PARTS_LIST = Lists.newArrayList(); private static final List<Part> RENDERED_PARTS = Lists.newArrayList(); // unspecified part is for parts without roles that get opened public static final Part UNSPECIFIED = createPart("Unspecified", "UNS", "unspecified.png",
ImageType.TALL_OVER_BASELINE, false, SequenceOntology.SEQUENCE_FEATURE);
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLEditorAction.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/swing/Buttons.java // public class Buttons { // public static JButton createButton(String text, Icon icon) { // return setStyle(new JButton(text, icon)); // } // // public static JButton createButton(Action action) { // return setStyle(new JButton(action)); // } // // public static JButton setStyle(JButton button) { // button.addMouseListener(BUTTON_ROLLOVER); // button.setBorderPainted(false); // button.setContentAreaFilled(false); // button.setFocusPainted(false); // return button; // } // // public static JToggleButton createToggleButton(String text, Icon icon) { // final JToggleButton button = new JToggleButton(text, icon); // return button; // } // // public static JToggleButton createToggleButton(Action action) { // final JToggleButton button = new JToggleButton(action); // button.setFocusPainted(false); // return button; // } // // // private static final MouseListener BUTTON_ROLLOVER = new MouseAdapter() { // public void mouseEntered(MouseEvent event) { // AbstractButton button = (AbstractButton) event.getSource(); // if (button.isEnabled()) { // button.setBorderPainted(true); // button.setContentAreaFilled(true); // } // } // // public void mouseExited(MouseEvent event) { // AbstractButton button = (AbstractButton) event.getSource(); // button.setBorderPainted(false); // button.setContentAreaFilled(false); // } // }; // // }
import java.awt.Image; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JMenuItem; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import edu.utah.ece.async.sboldesigner.swing.Buttons;
} } return null; } public SBOLEditorAction toggle() { isToggle = true; return this; } public SBOLEditorAction precondition(Supplier<Boolean> precondition) { this.precondition = precondition; return this; } public SBOLEditorAction allowed(boolean allowed) { this.allowed = allowed; return this; } protected abstract void perform(); public final void actionPerformed(ActionEvent e) { if (Boolean.TRUE.equals(precondition.get())) { perform(); } } protected AbstractButton createButton() { Preconditions.checkState(allowed, "This action is not allowed");
// Path: src/main/java/edu/utah/ece/async/sboldesigner/swing/Buttons.java // public class Buttons { // public static JButton createButton(String text, Icon icon) { // return setStyle(new JButton(text, icon)); // } // // public static JButton createButton(Action action) { // return setStyle(new JButton(action)); // } // // public static JButton setStyle(JButton button) { // button.addMouseListener(BUTTON_ROLLOVER); // button.setBorderPainted(false); // button.setContentAreaFilled(false); // button.setFocusPainted(false); // return button; // } // // public static JToggleButton createToggleButton(String text, Icon icon) { // final JToggleButton button = new JToggleButton(text, icon); // return button; // } // // public static JToggleButton createToggleButton(Action action) { // final JToggleButton button = new JToggleButton(action); // button.setFocusPainted(false); // return button; // } // // // private static final MouseListener BUTTON_ROLLOVER = new MouseAdapter() { // public void mouseEntered(MouseEvent event) { // AbstractButton button = (AbstractButton) event.getSource(); // if (button.isEnabled()) { // button.setBorderPainted(true); // button.setContentAreaFilled(true); // } // } // // public void mouseExited(MouseEvent event) { // AbstractButton button = (AbstractButton) event.getSource(); // button.setBorderPainted(false); // button.setContentAreaFilled(false); // } // }; // // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLEditorAction.java import java.awt.Image; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JMenuItem; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import edu.utah.ece.async.sboldesigner.swing.Buttons; } } return null; } public SBOLEditorAction toggle() { isToggle = true; return this; } public SBOLEditorAction precondition(Supplier<Boolean> precondition) { this.precondition = precondition; return this; } public SBOLEditorAction allowed(boolean allowed) { this.allowed = allowed; return this; } protected abstract void perform(); public final void actionPerformed(ActionEvent e) { if (Boolean.TRUE.equals(precondition.get())) { perform(); } } protected AbstractButton createButton() { Preconditions.checkState(allowed, "This action is not allowed");
final AbstractButton button = isToggle ? Buttons.createToggleButton(this) : Buttons.createButton(this);
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe;
private JComponent createButton(final ComponentDefinition comp, final Image image) { final int width = image.getWidth(null); final int height = image.getHeight(null); // JComponent button = Buttons.createButton("", new // ImageIcon(Images.scaleImage(img, 0.6))) { // // }; final JPanel button = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); double scale = Math.min(0.8, (double) getWidth() / width); g.drawImage(image, 0, 0, (int) (width * scale), (int) (height * scale), this); // g.drawImage(Images.scaleImage(image, scale), 0, 0, null); } }; button.setOpaque(false); button.putClientProperty("comp", comp); final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) {
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe; private JComponent createButton(final ComponentDefinition comp, final Image image) { final int width = image.getWidth(null); final int height = image.getHeight(null); // JComponent button = Buttons.createButton("", new // ImageIcon(Images.scaleImage(img, 0.6))) { // // }; final JPanel button = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); double scale = Math.min(0.8, (double) getWidth() / width); g.drawImage(image, 0, 0, (int) (width * scale), (int) (height * scale), this); // g.drawImage(Images.scaleImage(image, scale), 0, 0, null); } }; button.setOpaque(false); button.putClientProperty("comp", comp); final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) {
MessageDialog.showMessage(null, "There was an error: ", e1.getMessage());
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe;
double scale = Math.min(0.8, (double) getWidth() / width); g.drawImage(image, 0, 0, (int) (width * scale), (int) (height * scale), this); // g.drawImage(Images.scaleImage(image, scale), 0, 0, null); } }; button.setOpaque(false); button.putClientProperty("comp", comp); final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe; double scale = Math.min(0.8, (double) getWidth() / width); g.drawImage(image, 0, 0, (int) (width * scale), (int) (height * scale), this); // g.drawImage(Images.scaleImage(image, scale), 0, 0, null); } }; button.setOpaque(false); button.putClientProperty("comp", comp); final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe
public void designLoaded(DesignLoadedEvent event) {
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe;
final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe public void designLoaded(DesignLoadedEvent event) { while (count > 0) { remove(--count); } repaint(); } @Subscribe
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe; final ComponentDefinition parentComponent = editor.getDesign().getParentCD(); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe public void designLoaded(DesignLoadedEvent event) { while (count > 0) { remove(--count); } repaint(); } @Subscribe
public void focusedIn(FocusInEvent event) {
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe;
try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe public void designLoaded(DesignLoadedEvent event) { while (count > 0) { remove(--count); } repaint(); } @Subscribe public void focusedIn(FocusInEvent event) { addButton(event.getComponent(), event.getSnapshot()); } @Subscribe
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignLoadedEvent.java // public class DesignLoadedEvent { // private final SBOLDesign design; // // public DesignLoadedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusInEvent.java // public class FocusInEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // private final BufferedImage snapshot; // // public FocusInEvent(SBOLDesign design, ComponentDefinition component, BufferedImage snapshot) { // this.design = design; // this.component = component; // this.snapshot = snapshot; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // // public BufferedImage getSnapshot() { // return snapshot; // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/FocusOutEvent.java // public class FocusOutEvent { // private final SBOLDesign design; // private final ComponentDefinition component; // // public FocusOutEvent(SBOLDesign design, ComponentDefinition component) { // this.design = design; // this.component = component; // } // // public SBOLDesign getDesign() { // return design; // } // // public ComponentDefinition getComponent() { // return component; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/OverviewPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignLoadedEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusInEvent; import edu.utah.ece.async.sboldesigner.sbol.editor.event.FocusOutEvent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.eventbus.Subscribe; try { editor.getDesign().focusOut(parentComponent); } catch (SBOLValidationException e1) { MessageDialog.showMessage(null, "There was an error: ", e1.getMessage()); e1.printStackTrace(); } } }); return button; } private void addButton(final ComponentDefinition comp, final Image image) { add(createButton(comp, image), count++); } @Subscribe public void designLoaded(DesignLoadedEvent event) { while (count > 0) { remove(--count); } repaint(); } @Subscribe public void focusedIn(FocusInEvent event) { addButton(event.getComponent(), event.getSnapshot()); } @Subscribe
public void focusedOut(FocusOutEvent event) {
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/PartsPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignChangedEvent.java // public class DesignChangedEvent { // private final SBOLDesign design; // // public DesignChangedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignChangedEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.collect.Maps; import com.google.common.eventbus.Subscribe;
for (Part part : Parts.all()) { if (part.inPalette()) { addPartButton(part); } } editor.getEventBus().register(this); } private void addPartButton(final Part part) { JButton button = createPartButton(part); add(button); buttons.put(part, button); } private JButton createPartButton(final Part part) { JButton button = new JButton(); button.setText(part.getDisplayId()); button.setIcon(new ImageIcon(part.getImage())); button.setVerticalTextPosition(SwingConstants.BOTTOM); button.setHorizontalTextPosition(SwingConstants.CENTER); button.setToolTipText(part.getName()); button.setFocusPainted(false); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { design.addCD(part, part == Parts.UNSPECIFIED); } catch (SBOLValidationException | URISyntaxException e) {
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignChangedEvent.java // public class DesignChangedEvent { // private final SBOLDesign design; // // public DesignChangedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/PartsPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignChangedEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.collect.Maps; import com.google.common.eventbus.Subscribe; for (Part part : Parts.all()) { if (part.inPalette()) { addPartButton(part); } } editor.getEventBus().register(this); } private void addPartButton(final Part part) { JButton button = createPartButton(part); add(button); buttons.put(part, button); } private JButton createPartButton(final Part part) { JButton button = new JButton(); button.setText(part.getDisplayId()); button.setIcon(new ImageIcon(part.getImage())); button.setVerticalTextPosition(SwingConstants.BOTTOM); button.setHorizontalTextPosition(SwingConstants.CENTER); button.setToolTipText(part.getName()); button.setFocusPainted(false); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { design.addCD(part, part == Parts.UNSPECIFIED); } catch (SBOLValidationException | URISyntaxException e) {
MessageDialog.showMessage(null, "There was an error: ", e.getMessage());
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/PartsPanel.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignChangedEvent.java // public class DesignChangedEvent { // private final SBOLDesign design; // // public DesignChangedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // }
import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignChangedEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.collect.Maps; import com.google.common.eventbus.Subscribe;
private void addPartButton(final Part part) { JButton button = createPartButton(part); add(button); buttons.put(part, button); } private JButton createPartButton(final Part part) { JButton button = new JButton(); button.setText(part.getDisplayId()); button.setIcon(new ImageIcon(part.getImage())); button.setVerticalTextPosition(SwingConstants.BOTTOM); button.setHorizontalTextPosition(SwingConstants.CENTER); button.setToolTipText(part.getName()); button.setFocusPainted(false); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { design.addCD(part, part == Parts.UNSPECIFIED); } catch (SBOLValidationException | URISyntaxException e) { MessageDialog.showMessage(null, "There was an error: ", e.getMessage()); e.printStackTrace(); } } }); return button; } @Subscribe
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/MessageDialog.java // public class MessageDialog { // // public static void showMessage(Component parentComponent, String title, List<String> messages) { // StringBuilder sb = new StringBuilder(); // for (String message : messages) { // sb.append(message); // sb.append("\n"); // } // showMessage(parentComponent, title, sb.toString()); // } // // public static void showMessage(Component parentComponent, String title, String message) { // JTextArea jta = new JTextArea(message); // jta.setLineWrap(true); // jta.setWrapStyleWord(true); // jta.setEditable(false); // JScrollPane jsp = new JScrollPane(jta) { // @Override // public Dimension getPreferredSize() { // return new Dimension(580, 320); // } // }; // JOptionPane.showMessageDialog(parentComponent, jsp, title, JOptionPane.ERROR_MESSAGE); // } // } // // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/event/DesignChangedEvent.java // public class DesignChangedEvent { // private final SBOLDesign design; // // public DesignChangedEvent(SBOLDesign design) { // this.design = design; // } // // public SBOLDesign getDesign() { // return design; // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/PartsPanel.java import edu.utah.ece.async.sboldesigner.sbol.editor.dialog.MessageDialog; import edu.utah.ece.async.sboldesigner.sbol.editor.event.DesignChangedEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.sbolstandard.core2.SBOLValidationException; import com.google.common.collect.Maps; import com.google.common.eventbus.Subscribe; private void addPartButton(final Part part) { JButton button = createPartButton(part); add(button); buttons.put(part, button); } private JButton createPartButton(final Part part) { JButton button = new JButton(); button.setText(part.getDisplayId()); button.setIcon(new ImageIcon(part.getImage())); button.setVerticalTextPosition(SwingConstants.BOTTOM); button.setHorizontalTextPosition(SwingConstants.CENTER); button.setToolTipText(part.getName()); button.setFocusPainted(false); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { design.addCD(part, part == Parts.UNSPECIFIED); } catch (SBOLValidationException | URISyntaxException e) { MessageDialog.showMessage(null, "There was an error: ", e.getMessage()); e.printStackTrace(); } } }); return button; } @Subscribe
public void designChanged(DesignChangedEvent event) {
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/AboutDialog.java
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLDesignerMetadata.java // public class SBOLDesignerMetadata { // private SBOLDesignerMetadata() { // }; // // public static final String NAME = "SBOLDesigner"; // // public static final String AUTHORS = "the University of Utah, the University of Washington, and Clark & Parsia, LLC"; // // public static final String HOME_PAGE = "http://www.async.ece.utah.edu/SBOLDesigner"; // // public static final String EMAIL = "michael13162@gmail.com"; // // public static final String VERSION = readVersion(); // // private static String readVersion() { // Properties versionProperties = new Properties(); // // // InputStream vstream = // // SBOLVersion.class.getResourceAsStream("/plugin.properties"); // // if (vstream != null) { // // try { // // versionProperties.load(vstream); // // } // // catch (IOException e) { // // System.err.println("Could not load version properties:"); // // e.printStackTrace(); // // } // // finally { // // try { // // vstream.close(); // // } // // catch (IOException e) { // // System.err.println("Could not close version properties:"); // // e.printStackTrace(); // // } // // } // // } // // return versionProperties.getProperty("plugin-version", "3"); // } // }
import java.awt.Component; import java.awt.Font; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLDesignerMetadata;
/* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.ece.async.sboldesigner.sbol.editor.dialog; public class AboutDialog { private AboutDialog() { } public static void show(final Component parent) { // for copying style JLabel label = new JLabel(); Font font = label.getFont(); // create some css from the label's font StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); style.append("font-size:" + font.getSize() + "pt;"); // html content JEditorPane ep = new JEditorPane( "text/html", "<html><body style=\"" + style+ "\">"
// Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/SBOLDesignerMetadata.java // public class SBOLDesignerMetadata { // private SBOLDesignerMetadata() { // }; // // public static final String NAME = "SBOLDesigner"; // // public static final String AUTHORS = "the University of Utah, the University of Washington, and Clark & Parsia, LLC"; // // public static final String HOME_PAGE = "http://www.async.ece.utah.edu/SBOLDesigner"; // // public static final String EMAIL = "michael13162@gmail.com"; // // public static final String VERSION = readVersion(); // // private static String readVersion() { // Properties versionProperties = new Properties(); // // // InputStream vstream = // // SBOLVersion.class.getResourceAsStream("/plugin.properties"); // // if (vstream != null) { // // try { // // versionProperties.load(vstream); // // } // // catch (IOException e) { // // System.err.println("Could not load version properties:"); // // e.printStackTrace(); // // } // // finally { // // try { // // vstream.close(); // // } // // catch (IOException e) { // // System.err.println("Could not close version properties:"); // // e.printStackTrace(); // // } // // } // // } // // return versionProperties.getProperty("plugin-version", "3"); // } // } // Path: src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/AboutDialog.java import java.awt.Component; import java.awt.Font; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLDesignerMetadata; /* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.utah.ece.async.sboldesigner.sbol.editor.dialog; public class AboutDialog { private AboutDialog() { } public static void show(final Component parent) { // for copying style JLabel label = new JLabel(); Font font = label.getFont(); // create some css from the label's font StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); style.append("font-size:" + font.getSize() + "pt;"); // html content JEditorPane ep = new JEditorPane( "text/html", "<html><body style=\"" + style+ "\">"
+ SBOLDesignerMetadata.NAME + " v" + SBOLDesignerMetadata.VERSION
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/data/local/Db.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/util/DataUtils.java // public class DataUtils { // // //TODO: Implement network checks // public static boolean isNetworkAvailable(Context context) { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // return connectivityManager.getActiveNetworkInfo() != null; // } // // public static Gson getGsonInstance() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSz") // .create(); // } // // public static LatLngBounds latitudeLongitudeToBounds(LatLng center, double radius) { // LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225); // LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45); // return new LatLngBounds(southwest, northeast); // } // // }
import android.content.ContentValues; import android.database.Cursor; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.gson.Gson; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.hitherejoe.pickr.util.DataUtils;
package com.hitherejoe.pickr.data.local; public class Db { public Db() { } public static abstract class PointOfInterestTable { public static final String TABLE_NAME = "point_of_interests"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_LAT_LNG = "lat_lng"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_LAT_LNG_BOUNDS = "lat_lng_bounds"; public static final String CREATE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " TEXT PRIMARY KEY NOT NULL," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_ADDRESS + " TEXT NOT NULL," + COLUMN_LAT_LNG + " TEXT NOT NULL," + COLUMN_PHONE + " TEXT NOT NULL," + COLUMN_LAT_LNG_BOUNDS + " TEXT NOT NULL" + " ); ";
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/util/DataUtils.java // public class DataUtils { // // //TODO: Implement network checks // public static boolean isNetworkAvailable(Context context) { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // return connectivityManager.getActiveNetworkInfo() != null; // } // // public static Gson getGsonInstance() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSz") // .create(); // } // // public static LatLngBounds latitudeLongitudeToBounds(LatLng center, double radius) { // LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225); // LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45); // return new LatLngBounds(southwest, northeast); // } // // } // Path: app/src/main/java/com/hitherejoe/pickr/data/local/Db.java import android.content.ContentValues; import android.database.Cursor; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.gson.Gson; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.hitherejoe.pickr.util.DataUtils; package com.hitherejoe.pickr.data.local; public class Db { public Db() { } public static abstract class PointOfInterestTable { public static final String TABLE_NAME = "point_of_interests"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_LAT_LNG = "lat_lng"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_LAT_LNG_BOUNDS = "lat_lng_bounds"; public static final String CREATE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " TEXT PRIMARY KEY NOT NULL," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_ADDRESS + " TEXT NOT NULL," + COLUMN_LAT_LNG + " TEXT NOT NULL," + COLUMN_PHONE + " TEXT NOT NULL," + COLUMN_LAT_LNG_BOUNDS + " TEXT NOT NULL" + " ); ";
public static ContentValues toContentValues(PointOfInterest pointOfInterest) {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/data/local/Db.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/util/DataUtils.java // public class DataUtils { // // //TODO: Implement network checks // public static boolean isNetworkAvailable(Context context) { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // return connectivityManager.getActiveNetworkInfo() != null; // } // // public static Gson getGsonInstance() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSz") // .create(); // } // // public static LatLngBounds latitudeLongitudeToBounds(LatLng center, double radius) { // LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225); // LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45); // return new LatLngBounds(southwest, northeast); // } // // }
import android.content.ContentValues; import android.database.Cursor; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.gson.Gson; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.hitherejoe.pickr.util.DataUtils;
package com.hitherejoe.pickr.data.local; public class Db { public Db() { } public static abstract class PointOfInterestTable { public static final String TABLE_NAME = "point_of_interests"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_LAT_LNG = "lat_lng"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_LAT_LNG_BOUNDS = "lat_lng_bounds"; public static final String CREATE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " TEXT PRIMARY KEY NOT NULL," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_ADDRESS + " TEXT NOT NULL," + COLUMN_LAT_LNG + " TEXT NOT NULL," + COLUMN_PHONE + " TEXT NOT NULL," + COLUMN_LAT_LNG_BOUNDS + " TEXT NOT NULL" + " ); "; public static ContentValues toContentValues(PointOfInterest pointOfInterest) {
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/util/DataUtils.java // public class DataUtils { // // //TODO: Implement network checks // public static boolean isNetworkAvailable(Context context) { // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // return connectivityManager.getActiveNetworkInfo() != null; // } // // public static Gson getGsonInstance() { // return new GsonBuilder() // .setDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSz") // .create(); // } // // public static LatLngBounds latitudeLongitudeToBounds(LatLng center, double radius) { // LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225); // LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45); // return new LatLngBounds(southwest, northeast); // } // // } // Path: app/src/main/java/com/hitherejoe/pickr/data/local/Db.java import android.content.ContentValues; import android.database.Cursor; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.gson.Gson; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.hitherejoe.pickr.util.DataUtils; package com.hitherejoe.pickr.data.local; public class Db { public Db() { } public static abstract class PointOfInterestTable { public static final String TABLE_NAME = "point_of_interests"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_LAT_LNG = "lat_lng"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_LAT_LNG_BOUNDS = "lat_lng_bounds"; public static final String CREATE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " TEXT PRIMARY KEY NOT NULL," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_ADDRESS + " TEXT NOT NULL," + COLUMN_LAT_LNG + " TEXT NOT NULL," + COLUMN_PHONE + " TEXT NOT NULL," + COLUMN_LAT_LNG_BOUNDS + " TEXT NOT NULL" + " ); "; public static ContentValues toContentValues(PointOfInterest pointOfInterest) {
Gson gson = DataUtils.getGsonInstance();
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.hitherejoe.pickr.R; import com.hitherejoe.pickr.data.model.PointOfInterest; import butterknife.Bind; import butterknife.ButterKnife;
package com.hitherejoe.pickr.ui.activity; public class DetailActivity extends BaseActivity implements OnMapReadyCallback { @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.layout_name) LinearLayout mNameLayout; @Bind(R.id.text_name) TextView mNameText; @Bind(R.id.layout_address) LinearLayout mAddressLayout; @Bind(R.id.text_address) TextView mAddressText; @Bind(R.id.layout_phone_number) LinearLayout mPhoneNumberLayout; @Bind(R.id.text_phone_number) TextView mPhoneNumberText; private static final String EXTRA_POI = "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI";
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.hitherejoe.pickr.R; import com.hitherejoe.pickr.data.model.PointOfInterest; import butterknife.Bind; import butterknife.ButterKnife; package com.hitherejoe.pickr.ui.activity; public class DetailActivity extends BaseActivity implements OnMapReadyCallback { @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.layout_name) LinearLayout mNameLayout; @Bind(R.id.text_name) TextView mNameText; @Bind(R.id.layout_address) LinearLayout mAddressLayout; @Bind(R.id.text_address) TextView mAddressText; @Bind(R.id.layout_phone_number) LinearLayout mPhoneNumberLayout; @Bind(R.id.text_phone_number) TextView mPhoneNumberText; private static final String EXTRA_POI = "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI";
private PointOfInterest mPointOfInterest;
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // }
import android.content.Context; import android.database.Cursor; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.functions.Func1;
package com.hitherejoe.pickr.data.local; public class DatabaseHelper { private BriteDatabase mBriteDb; public DatabaseHelper(Context context) { mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); } public BriteDatabase getBriteDb() { return mBriteDb; }
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // Path: app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java import android.content.Context; import android.database.Cursor; import com.hitherejoe.pickr.data.model.PointOfInterest; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; package com.hitherejoe.pickr.data.local; public class DatabaseHelper { private BriteDatabase mBriteDb; public DatabaseHelper(Context context) { mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); } public BriteDatabase getBriteDb() { return mBriteDb; }
public Observable<PointOfInterest> saveLocation(final PointOfInterest pointOfInterest) {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/injection/module/ApplicationModule.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/DataManager.java // public class DataManager { // // @Inject protected DatabaseHelper mDatabaseHelper; // @Inject protected Scheduler mSubscribeScheduler; // @Inject protected Bus mEventBus; // // public DataManager(Context context) { // injectDependencies(context); // } // // /* This constructor is provided so we can set up a DataManager with mocks from unit test. // * At the moment this is not possible to do with Dagger because the Gradle APT plugin doesn't // * work for the unit test variant, plus Dagger 2 doesn't provide a nice way of overriding // * modules */ // public DataManager(DatabaseHelper databaseHelper, // Bus eventBus, // Scheduler subscribeScheduler) { // mDatabaseHelper = databaseHelper; // mEventBus = eventBus; // mSubscribeScheduler = subscribeScheduler; // } // // protected void injectDependencies(Context context) { // DaggerDataManagerComponent.builder() // .applicationComponent(PickrApplication.get(context).getComponent()) // .dataManagerModule(new DataManagerModule(context)) // .build() // .inject(this); // } // // public Scheduler getScheduler() { // return mSubscribeScheduler; // } // // public Observable<List<PointOfInterest>> getLocations() { // return mDatabaseHelper.getLocations(); // } // // public Observable<PointOfInterest> saveLocation(final Context context, final PointOfInterest pointOfInterest) { // // return doesLocationExist(pointOfInterest.id).flatMap(new Func1<Boolean, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(Boolean doesLocationExist) { // if (doesLocationExist) return Observable.just(null); // // return mDatabaseHelper.saveLocation(pointOfInterest).doOnCompleted(new Action0() { // @Override // public void call() { // postEventSafely(context, new BusEvent.PlaceAdded()); // } // }); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(PointOfInterest pointOfInterest) { // return mDatabaseHelper.deleteLocation(pointOfInterest); // } // // public Observable<PlacePrediction> getAutocompleteResults(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return Observable.create(new Observable.OnSubscribe<PlacePrediction>() { // @Override // public void call(Subscriber<? super PlacePrediction> subscriber) { // // PendingResult<AutocompletePredictionBuffer> results = // Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query, // bounds, null); // // AutocompletePredictionBuffer autocompletePredictions = results // .await(60, TimeUnit.SECONDS); // // final Status status = autocompletePredictions.getStatus(); // if (!status.isSuccess()) { // autocompletePredictions.release(); // subscriber.onError(null); // } else { // for (AutocompletePrediction autocompletePrediction : autocompletePredictions) { // subscriber.onNext( // new PlacePrediction( // autocompletePrediction.getPlaceId(), // autocompletePrediction.getDescription() // )); // } // autocompletePredictions.release(); // subscriber.onCompleted(); // } // } // }); // } // // public Observable<Boolean> doesLocationExist(String id) { // return mDatabaseHelper.getLocation(id).flatMap(new Func1<PointOfInterest, Observable<Boolean>>() { // @Override // public Observable<Boolean> call(PointOfInterest pointOfInterest) { // return Observable.just(pointOfInterest != null); // } // }); // } // // public Observable<PointOfInterest> getPredictions(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return getAutocompleteResults(mGoogleApiClient, query, bounds) // .flatMap(new Func1<PlacePrediction, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(PlacePrediction placePrediction) { // return getCompleteResult(mGoogleApiClient, placePrediction.placeId.toString()); // } // }); // } // // public Observable<PointOfInterest> getCompleteResult(final GoogleApiClient mGoogleApiClient, final String id) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(final Subscriber<? super PointOfInterest> subscriber) { // final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi // .getPlaceById(mGoogleApiClient, id); // placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { // @Override // public void onResult(PlaceBuffer places) { // if (!places.getStatus().isSuccess()) { // places.release(); // subscriber.onError(null); // } else { // subscriber.onNext(PointOfInterest.fromPlace(places.get(0))); // places.close(); // subscriber.onCompleted(); // } // } // }); // } // }); // } // // private void postEventSafely(final Context context, final Object event) { // new Handler(Looper.getMainLooper()).post(new Runnable() { // @Override // public void run() { // PickrApplication.get(context).getComponent().eventBus().post(event); // } // }); // } // // }
import android.app.Application; import com.hitherejoe.pickr.data.DataManager; import com.squareup.otto.Bus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.hitherejoe.pickr.injection.module; /** * Provide application-level dependencies. Mainly singleton object that can be injected from * anywhere in the app. */ @Module public class ApplicationModule { protected final Application mApplication; public ApplicationModule(Application application) { mApplication = application; } @Provides @Singleton Application provideApplication() { return mApplication; } @Provides @Singleton
// Path: app/src/main/java/com/hitherejoe/pickr/data/DataManager.java // public class DataManager { // // @Inject protected DatabaseHelper mDatabaseHelper; // @Inject protected Scheduler mSubscribeScheduler; // @Inject protected Bus mEventBus; // // public DataManager(Context context) { // injectDependencies(context); // } // // /* This constructor is provided so we can set up a DataManager with mocks from unit test. // * At the moment this is not possible to do with Dagger because the Gradle APT plugin doesn't // * work for the unit test variant, plus Dagger 2 doesn't provide a nice way of overriding // * modules */ // public DataManager(DatabaseHelper databaseHelper, // Bus eventBus, // Scheduler subscribeScheduler) { // mDatabaseHelper = databaseHelper; // mEventBus = eventBus; // mSubscribeScheduler = subscribeScheduler; // } // // protected void injectDependencies(Context context) { // DaggerDataManagerComponent.builder() // .applicationComponent(PickrApplication.get(context).getComponent()) // .dataManagerModule(new DataManagerModule(context)) // .build() // .inject(this); // } // // public Scheduler getScheduler() { // return mSubscribeScheduler; // } // // public Observable<List<PointOfInterest>> getLocations() { // return mDatabaseHelper.getLocations(); // } // // public Observable<PointOfInterest> saveLocation(final Context context, final PointOfInterest pointOfInterest) { // // return doesLocationExist(pointOfInterest.id).flatMap(new Func1<Boolean, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(Boolean doesLocationExist) { // if (doesLocationExist) return Observable.just(null); // // return mDatabaseHelper.saveLocation(pointOfInterest).doOnCompleted(new Action0() { // @Override // public void call() { // postEventSafely(context, new BusEvent.PlaceAdded()); // } // }); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(PointOfInterest pointOfInterest) { // return mDatabaseHelper.deleteLocation(pointOfInterest); // } // // public Observable<PlacePrediction> getAutocompleteResults(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return Observable.create(new Observable.OnSubscribe<PlacePrediction>() { // @Override // public void call(Subscriber<? super PlacePrediction> subscriber) { // // PendingResult<AutocompletePredictionBuffer> results = // Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query, // bounds, null); // // AutocompletePredictionBuffer autocompletePredictions = results // .await(60, TimeUnit.SECONDS); // // final Status status = autocompletePredictions.getStatus(); // if (!status.isSuccess()) { // autocompletePredictions.release(); // subscriber.onError(null); // } else { // for (AutocompletePrediction autocompletePrediction : autocompletePredictions) { // subscriber.onNext( // new PlacePrediction( // autocompletePrediction.getPlaceId(), // autocompletePrediction.getDescription() // )); // } // autocompletePredictions.release(); // subscriber.onCompleted(); // } // } // }); // } // // public Observable<Boolean> doesLocationExist(String id) { // return mDatabaseHelper.getLocation(id).flatMap(new Func1<PointOfInterest, Observable<Boolean>>() { // @Override // public Observable<Boolean> call(PointOfInterest pointOfInterest) { // return Observable.just(pointOfInterest != null); // } // }); // } // // public Observable<PointOfInterest> getPredictions(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return getAutocompleteResults(mGoogleApiClient, query, bounds) // .flatMap(new Func1<PlacePrediction, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(PlacePrediction placePrediction) { // return getCompleteResult(mGoogleApiClient, placePrediction.placeId.toString()); // } // }); // } // // public Observable<PointOfInterest> getCompleteResult(final GoogleApiClient mGoogleApiClient, final String id) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(final Subscriber<? super PointOfInterest> subscriber) { // final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi // .getPlaceById(mGoogleApiClient, id); // placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { // @Override // public void onResult(PlaceBuffer places) { // if (!places.getStatus().isSuccess()) { // places.release(); // subscriber.onError(null); // } else { // subscriber.onNext(PointOfInterest.fromPlace(places.get(0))); // places.close(); // subscriber.onCompleted(); // } // } // }); // } // }); // } // // private void postEventSafely(final Context context, final Object event) { // new Handler(Looper.getMainLooper()).post(new Runnable() { // @Override // public void run() { // PickrApplication.get(context).getComponent().eventBus().post(event); // } // }); // } // // } // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/ApplicationModule.java import android.app.Application; import com.hitherejoe.pickr.data.DataManager; import com.squareup.otto.Bus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.hitherejoe.pickr.injection.module; /** * Provide application-level dependencies. Mainly singleton object that can be injected from * anywhere in the app. */ @Module public class ApplicationModule { protected final Application mApplication; public ApplicationModule(Application application) { mApplication = application; } @Provides @Singleton Application provideApplication() { return mApplication; } @Provides @Singleton
DataManager provideDataManager() {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/PickrApplication.java
// Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/ApplicationModule.java // @Module // public class ApplicationModule { // protected final Application mApplication; // // public ApplicationModule(Application application) { // mApplication = application; // } // // @Provides // @Singleton // Application provideApplication() { // return mApplication; // } // // @Provides // @Singleton // DataManager provideDataManager() { // return new DataManager(mApplication); // } // // @Provides // @Singleton // Bus provideEventBus() { // return new Bus(); // } // // }
import android.app.Application; import android.content.Context; import com.hitherejoe.pickr.injection.component.ApplicationComponent; import com.hitherejoe.pickr.injection.component.DaggerApplicationComponent; import com.hitherejoe.pickr.injection.module.ApplicationModule; import timber.log.Timber;
package com.hitherejoe.pickr; public class PickrApplication extends Application { ApplicationComponent mApplicationComponent; @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); mApplicationComponent = DaggerApplicationComponent.builder()
// Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/ApplicationModule.java // @Module // public class ApplicationModule { // protected final Application mApplication; // // public ApplicationModule(Application application) { // mApplication = application; // } // // @Provides // @Singleton // Application provideApplication() { // return mApplication; // } // // @Provides // @Singleton // DataManager provideDataManager() { // return new DataManager(mApplication); // } // // @Provides // @Singleton // Bus provideEventBus() { // return new Bus(); // } // // } // Path: app/src/main/java/com/hitherejoe/pickr/PickrApplication.java import android.app.Application; import android.content.Context; import com.hitherejoe.pickr.injection.component.ApplicationComponent; import com.hitherejoe.pickr.injection.component.DaggerApplicationComponent; import com.hitherejoe.pickr.injection.module.ApplicationModule; import timber.log.Timber; package com.hitherejoe.pickr; public class PickrApplication extends Application { ApplicationComponent mApplicationComponent; @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/ui/activity/BaseActivity.java
// Path: app/src/main/java/com/hitherejoe/pickr/PickrApplication.java // public class PickrApplication extends Application { // // ApplicationComponent mApplicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); // // mApplicationComponent = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .build(); // } // // public static PickrApplication get(Context context) { // return (PickrApplication) context.getApplicationContext(); // } // // public ApplicationComponent getComponent() { // return mApplicationComponent; // } // // // Needed to replace the component with a test specific one // public void setComponent(ApplicationComponent applicationComponent) { // mApplicationComponent = applicationComponent; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // }
import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.hitherejoe.pickr.PickrApplication; import com.hitherejoe.pickr.injection.component.ApplicationComponent;
package com.hitherejoe.pickr.ui.activity; public class BaseActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { finish(); } return true; default: return super.onOptionsItemSelected(item); } }
// Path: app/src/main/java/com/hitherejoe/pickr/PickrApplication.java // public class PickrApplication extends Application { // // ApplicationComponent mApplicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); // // mApplicationComponent = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .build(); // } // // public static PickrApplication get(Context context) { // return (PickrApplication) context.getApplicationContext(); // } // // public ApplicationComponent getComponent() { // return mApplicationComponent; // } // // // Needed to replace the component with a test specific one // public void setComponent(ApplicationComponent applicationComponent) { // mApplicationComponent = applicationComponent; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // } // Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/BaseActivity.java import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.hitherejoe.pickr.PickrApplication; import com.hitherejoe.pickr.injection.component.ApplicationComponent; package com.hitherejoe.pickr.ui.activity; public class BaseActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { finish(); } return true; default: return super.onOptionsItemSelected(item); } }
protected ApplicationComponent applicationComponent() {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/ui/activity/BaseActivity.java
// Path: app/src/main/java/com/hitherejoe/pickr/PickrApplication.java // public class PickrApplication extends Application { // // ApplicationComponent mApplicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); // // mApplicationComponent = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .build(); // } // // public static PickrApplication get(Context context) { // return (PickrApplication) context.getApplicationContext(); // } // // public ApplicationComponent getComponent() { // return mApplicationComponent; // } // // // Needed to replace the component with a test specific one // public void setComponent(ApplicationComponent applicationComponent) { // mApplicationComponent = applicationComponent; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // }
import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.hitherejoe.pickr.PickrApplication; import com.hitherejoe.pickr.injection.component.ApplicationComponent;
package com.hitherejoe.pickr.ui.activity; public class BaseActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { finish(); } return true; default: return super.onOptionsItemSelected(item); } } protected ApplicationComponent applicationComponent() {
// Path: app/src/main/java/com/hitherejoe/pickr/PickrApplication.java // public class PickrApplication extends Application { // // ApplicationComponent mApplicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); // // mApplicationComponent = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .build(); // } // // public static PickrApplication get(Context context) { // return (PickrApplication) context.getApplicationContext(); // } // // public ApplicationComponent getComponent() { // return mApplicationComponent; // } // // // Needed to replace the component with a test specific one // public void setComponent(ApplicationComponent applicationComponent) { // mApplicationComponent = applicationComponent; // } // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/component/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // void inject(MainActivity mainActivity); // // Application application(); // DataManager dataManager(); // Bus eventBus(); // } // Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/BaseActivity.java import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.hitherejoe.pickr.PickrApplication; import com.hitherejoe.pickr.injection.component.ApplicationComponent; package com.hitherejoe.pickr.ui.activity; public class BaseActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { finish(); } return true; default: return super.onOptionsItemSelected(item); } } protected ApplicationComponent applicationComponent() {
return PickrApplication.get(this).getComponent();
hitherejoe/Pickr
app/src/androidTest/java/com/hitherejoe/pickr/injection/module/DataManagerTestModule.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java // public class DatabaseHelper { // // private BriteDatabase mBriteDb; // // public DatabaseHelper(Context context) { // mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); // } // // public BriteDatabase getBriteDb() { // return mBriteDb; // } // // public Observable<PointOfInterest> saveLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.insert(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.toContentValues(pointOfInterest)); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.delete(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.COLUMN_ID + "=?", pointOfInterest.id); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> getLocation(final String id) { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME + // " WHERE " + Db.PointOfInterestTable.COLUMN_ID + "=?", id) // .map(new Func1<SqlBrite.Query, PointOfInterest>() { // @Override // public PointOfInterest call(SqlBrite.Query query) { // PointOfInterest result = null; // Cursor cursor = query.run(); // if (cursor.moveToFirst()) { // PointOfInterest pointOfInterest = // Db.PointOfInterestTable.parseCursor(cursor); // if (pointOfInterest.id.equals(id)) result = pointOfInterest; // } // cursor.close(); // return result; // } // }); // } // // public Observable<List<PointOfInterest>> getLocations() { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME) // .map(new Func1<SqlBrite.Query, List<PointOfInterest>>() { // @Override // public List<PointOfInterest> call(SqlBrite.Query query) { // Cursor cursor = query.run(); // List<PointOfInterest> result = new ArrayList<>(); // while (cursor.moveToNext()) { // result.add(Db.PointOfInterestTable.parseCursor(cursor)); // } // cursor.close(); // return result; // } // }); // } // // public Observable<Void> clearTables() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // mBriteDb.beginTransaction(); // try { // Cursor cursor = // mBriteDb.query("SELECT name FROM sqlite_master WHERE type='table'"); // while (cursor.moveToNext()) { // mBriteDb.delete(cursor.getString(cursor.getColumnIndex("name")), null); // } // cursor.close(); // mBriteDb.setTransactionSuccessful(); // subscriber.onCompleted(); // } finally { // mBriteDb.endTransaction(); // } // } // }); // } // // }
import android.content.Context; import com.hitherejoe.pickr.data.local.DatabaseHelper; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers;
package com.hitherejoe.pickr.injection.module; /** * Provides dependencies for an app running on a testing environment * This allows injecting mocks if necessary */ @Module public class DataManagerTestModule { private final Context mContext; public DataManagerTestModule(Context context) { mContext = context; } @Provides @PerDataManager
// Path: app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java // public class DatabaseHelper { // // private BriteDatabase mBriteDb; // // public DatabaseHelper(Context context) { // mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); // } // // public BriteDatabase getBriteDb() { // return mBriteDb; // } // // public Observable<PointOfInterest> saveLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.insert(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.toContentValues(pointOfInterest)); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.delete(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.COLUMN_ID + "=?", pointOfInterest.id); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> getLocation(final String id) { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME + // " WHERE " + Db.PointOfInterestTable.COLUMN_ID + "=?", id) // .map(new Func1<SqlBrite.Query, PointOfInterest>() { // @Override // public PointOfInterest call(SqlBrite.Query query) { // PointOfInterest result = null; // Cursor cursor = query.run(); // if (cursor.moveToFirst()) { // PointOfInterest pointOfInterest = // Db.PointOfInterestTable.parseCursor(cursor); // if (pointOfInterest.id.equals(id)) result = pointOfInterest; // } // cursor.close(); // return result; // } // }); // } // // public Observable<List<PointOfInterest>> getLocations() { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME) // .map(new Func1<SqlBrite.Query, List<PointOfInterest>>() { // @Override // public List<PointOfInterest> call(SqlBrite.Query query) { // Cursor cursor = query.run(); // List<PointOfInterest> result = new ArrayList<>(); // while (cursor.moveToNext()) { // result.add(Db.PointOfInterestTable.parseCursor(cursor)); // } // cursor.close(); // return result; // } // }); // } // // public Observable<Void> clearTables() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // mBriteDb.beginTransaction(); // try { // Cursor cursor = // mBriteDb.query("SELECT name FROM sqlite_master WHERE type='table'"); // while (cursor.moveToNext()) { // mBriteDb.delete(cursor.getString(cursor.getColumnIndex("name")), null); // } // cursor.close(); // mBriteDb.setTransactionSuccessful(); // subscriber.onCompleted(); // } finally { // mBriteDb.endTransaction(); // } // } // }); // } // // } // Path: app/src/androidTest/java/com/hitherejoe/pickr/injection/module/DataManagerTestModule.java import android.content.Context; import com.hitherejoe.pickr.data.local.DatabaseHelper; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; package com.hitherejoe.pickr.injection.module; /** * Provides dependencies for an app running on a testing environment * This allows injecting mocks if necessary */ @Module public class DataManagerTestModule { private final Context mContext; public DataManagerTestModule(Context context) { mContext = context; } @Provides @PerDataManager
DatabaseHelper provideDatabaseHelper() {
hitherejoe/Pickr
app/src/androidTest/java/com/hitherejoe/pickr/DetailActivityTest.java
// Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java // public class DetailActivity extends BaseActivity implements OnMapReadyCallback { // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.layout_name) // LinearLayout mNameLayout; // // @Bind(R.id.text_name) // TextView mNameText; // // @Bind(R.id.layout_address) // LinearLayout mAddressLayout; // // @Bind(R.id.text_address) // TextView mAddressText; // // @Bind(R.id.layout_phone_number) // LinearLayout mPhoneNumberLayout; // // @Bind(R.id.text_phone_number) // TextView mPhoneNumberText; // // private static final String EXTRA_POI = // "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI"; // // private PointOfInterest mPointOfInterest; // // public static Intent getStartIntent(Context context, PointOfInterest pointOfInterest) { // Intent intent = new Intent(context, DetailActivity.class); // intent.putExtra(EXTRA_POI, pointOfInterest); // return intent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_detail); // ButterKnife.bind(this); // mPointOfInterest = getIntent().getParcelableExtra(EXTRA_POI); // if (mPointOfInterest == null) { // throw new IllegalArgumentException("DetailActivity requires a Location object!"); // } // ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment_map)).getMapAsync(this); // setupToolbar(); // setupLocationData(); // } // // @Override // public void onMapReady(final GoogleMap googleMap) { // googleMap.setMyLocationEnabled(true); // googleMap.getUiSettings().setMyLocationButtonEnabled(true); // googleMap.getUiSettings().setMapToolbarEnabled(false); // LatLng latLng = mPointOfInterest.latLng; // if (latLng != null) { // googleMap.addMarker(new MarkerOptions().position(latLng) // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); // googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)); // } // } // // private void setupToolbar() { // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(mPointOfInterest.name); // } // } // // private void setupLocationData() { // String placeName = mPointOfInterest.name; // if (placeName != null && !placeName.isEmpty()) { // mNameText.setText(mPointOfInterest.name); // } else { // mNameLayout.setVisibility(View.GONE); // } // // String placeAddress = mPointOfInterest.address; // if (placeAddress != null && !placeAddress.isEmpty()) { // mAddressText.setText(placeAddress); // } else { // mAddressLayout.setVisibility(View.GONE); // } // // String placePhoneNumber = mPointOfInterest.phoneNumber; // if (placePhoneNumber != null && !placePhoneNumber.isEmpty()) { // mPhoneNumberText.setText(placePhoneNumber); // } else { // mPhoneNumberLayout.setVisibility(View.GONE); // } // } // // } // // Path: app/src/androidTest/java/com/hitherejoe/pickr/injection/TestComponentRule.java // public class TestComponentRule implements TestRule { // // private TestComponent mTestComponent; // // public TestDataManager getDataManager() { // return (TestDataManager) mTestComponent.dataManager(); // } // // public DatabaseHelper getDatabaseHelper() { // return getDataManager().getDatabaseHelper(); // } // // private void setupDaggerTestComponentInApplication() { // PickrApplication application = PickrApplication // .get(InstrumentationRegistry.getTargetContext()); // if (application.getComponent() instanceof TestComponent) { // mTestComponent = (TestComponent) application.getComponent(); // } else { // mTestComponent = DaggerTestComponent.builder() // .applicationTestModule(new ApplicationTestModule(application)) // .build(); // application.setComponent(mTestComponent); // } // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setupDaggerTestComponentInApplication(); // base.evaluate(); // } finally { // mTestComponent = null; // } // } // }; // } // }
import android.content.Context; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.hitherejoe.pickr.ui.activity.DetailActivity; import com.hitherejoe.pickr.injection.TestComponentRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.InstrumentationRegistry.getTargetContext;
package com.hitherejoe.pickr; @RunWith(AndroidJUnit4.class) public class DetailActivityTest { private Context mContext; @Rule
// Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java // public class DetailActivity extends BaseActivity implements OnMapReadyCallback { // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.layout_name) // LinearLayout mNameLayout; // // @Bind(R.id.text_name) // TextView mNameText; // // @Bind(R.id.layout_address) // LinearLayout mAddressLayout; // // @Bind(R.id.text_address) // TextView mAddressText; // // @Bind(R.id.layout_phone_number) // LinearLayout mPhoneNumberLayout; // // @Bind(R.id.text_phone_number) // TextView mPhoneNumberText; // // private static final String EXTRA_POI = // "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI"; // // private PointOfInterest mPointOfInterest; // // public static Intent getStartIntent(Context context, PointOfInterest pointOfInterest) { // Intent intent = new Intent(context, DetailActivity.class); // intent.putExtra(EXTRA_POI, pointOfInterest); // return intent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_detail); // ButterKnife.bind(this); // mPointOfInterest = getIntent().getParcelableExtra(EXTRA_POI); // if (mPointOfInterest == null) { // throw new IllegalArgumentException("DetailActivity requires a Location object!"); // } // ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment_map)).getMapAsync(this); // setupToolbar(); // setupLocationData(); // } // // @Override // public void onMapReady(final GoogleMap googleMap) { // googleMap.setMyLocationEnabled(true); // googleMap.getUiSettings().setMyLocationButtonEnabled(true); // googleMap.getUiSettings().setMapToolbarEnabled(false); // LatLng latLng = mPointOfInterest.latLng; // if (latLng != null) { // googleMap.addMarker(new MarkerOptions().position(latLng) // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); // googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)); // } // } // // private void setupToolbar() { // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(mPointOfInterest.name); // } // } // // private void setupLocationData() { // String placeName = mPointOfInterest.name; // if (placeName != null && !placeName.isEmpty()) { // mNameText.setText(mPointOfInterest.name); // } else { // mNameLayout.setVisibility(View.GONE); // } // // String placeAddress = mPointOfInterest.address; // if (placeAddress != null && !placeAddress.isEmpty()) { // mAddressText.setText(placeAddress); // } else { // mAddressLayout.setVisibility(View.GONE); // } // // String placePhoneNumber = mPointOfInterest.phoneNumber; // if (placePhoneNumber != null && !placePhoneNumber.isEmpty()) { // mPhoneNumberText.setText(placePhoneNumber); // } else { // mPhoneNumberLayout.setVisibility(View.GONE); // } // } // // } // // Path: app/src/androidTest/java/com/hitherejoe/pickr/injection/TestComponentRule.java // public class TestComponentRule implements TestRule { // // private TestComponent mTestComponent; // // public TestDataManager getDataManager() { // return (TestDataManager) mTestComponent.dataManager(); // } // // public DatabaseHelper getDatabaseHelper() { // return getDataManager().getDatabaseHelper(); // } // // private void setupDaggerTestComponentInApplication() { // PickrApplication application = PickrApplication // .get(InstrumentationRegistry.getTargetContext()); // if (application.getComponent() instanceof TestComponent) { // mTestComponent = (TestComponent) application.getComponent(); // } else { // mTestComponent = DaggerTestComponent.builder() // .applicationTestModule(new ApplicationTestModule(application)) // .build(); // application.setComponent(mTestComponent); // } // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setupDaggerTestComponentInApplication(); // base.evaluate(); // } finally { // mTestComponent = null; // } // } // }; // } // } // Path: app/src/androidTest/java/com/hitherejoe/pickr/DetailActivityTest.java import android.content.Context; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.hitherejoe.pickr.ui.activity.DetailActivity; import com.hitherejoe.pickr.injection.TestComponentRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.InstrumentationRegistry.getTargetContext; package com.hitherejoe.pickr; @RunWith(AndroidJUnit4.class) public class DetailActivityTest { private Context mContext; @Rule
public final ActivityTestRule<DetailActivity> main =
hitherejoe/Pickr
app/src/androidTest/java/com/hitherejoe/pickr/DetailActivityTest.java
// Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java // public class DetailActivity extends BaseActivity implements OnMapReadyCallback { // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.layout_name) // LinearLayout mNameLayout; // // @Bind(R.id.text_name) // TextView mNameText; // // @Bind(R.id.layout_address) // LinearLayout mAddressLayout; // // @Bind(R.id.text_address) // TextView mAddressText; // // @Bind(R.id.layout_phone_number) // LinearLayout mPhoneNumberLayout; // // @Bind(R.id.text_phone_number) // TextView mPhoneNumberText; // // private static final String EXTRA_POI = // "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI"; // // private PointOfInterest mPointOfInterest; // // public static Intent getStartIntent(Context context, PointOfInterest pointOfInterest) { // Intent intent = new Intent(context, DetailActivity.class); // intent.putExtra(EXTRA_POI, pointOfInterest); // return intent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_detail); // ButterKnife.bind(this); // mPointOfInterest = getIntent().getParcelableExtra(EXTRA_POI); // if (mPointOfInterest == null) { // throw new IllegalArgumentException("DetailActivity requires a Location object!"); // } // ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment_map)).getMapAsync(this); // setupToolbar(); // setupLocationData(); // } // // @Override // public void onMapReady(final GoogleMap googleMap) { // googleMap.setMyLocationEnabled(true); // googleMap.getUiSettings().setMyLocationButtonEnabled(true); // googleMap.getUiSettings().setMapToolbarEnabled(false); // LatLng latLng = mPointOfInterest.latLng; // if (latLng != null) { // googleMap.addMarker(new MarkerOptions().position(latLng) // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); // googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)); // } // } // // private void setupToolbar() { // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(mPointOfInterest.name); // } // } // // private void setupLocationData() { // String placeName = mPointOfInterest.name; // if (placeName != null && !placeName.isEmpty()) { // mNameText.setText(mPointOfInterest.name); // } else { // mNameLayout.setVisibility(View.GONE); // } // // String placeAddress = mPointOfInterest.address; // if (placeAddress != null && !placeAddress.isEmpty()) { // mAddressText.setText(placeAddress); // } else { // mAddressLayout.setVisibility(View.GONE); // } // // String placePhoneNumber = mPointOfInterest.phoneNumber; // if (placePhoneNumber != null && !placePhoneNumber.isEmpty()) { // mPhoneNumberText.setText(placePhoneNumber); // } else { // mPhoneNumberLayout.setVisibility(View.GONE); // } // } // // } // // Path: app/src/androidTest/java/com/hitherejoe/pickr/injection/TestComponentRule.java // public class TestComponentRule implements TestRule { // // private TestComponent mTestComponent; // // public TestDataManager getDataManager() { // return (TestDataManager) mTestComponent.dataManager(); // } // // public DatabaseHelper getDatabaseHelper() { // return getDataManager().getDatabaseHelper(); // } // // private void setupDaggerTestComponentInApplication() { // PickrApplication application = PickrApplication // .get(InstrumentationRegistry.getTargetContext()); // if (application.getComponent() instanceof TestComponent) { // mTestComponent = (TestComponent) application.getComponent(); // } else { // mTestComponent = DaggerTestComponent.builder() // .applicationTestModule(new ApplicationTestModule(application)) // .build(); // application.setComponent(mTestComponent); // } // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setupDaggerTestComponentInApplication(); // base.evaluate(); // } finally { // mTestComponent = null; // } // } // }; // } // }
import android.content.Context; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.hitherejoe.pickr.ui.activity.DetailActivity; import com.hitherejoe.pickr.injection.TestComponentRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.InstrumentationRegistry.getTargetContext;
package com.hitherejoe.pickr; @RunWith(AndroidJUnit4.class) public class DetailActivityTest { private Context mContext; @Rule public final ActivityTestRule<DetailActivity> main = new ActivityTestRule<>(DetailActivity.class, false, false); @Rule
// Path: app/src/main/java/com/hitherejoe/pickr/ui/activity/DetailActivity.java // public class DetailActivity extends BaseActivity implements OnMapReadyCallback { // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.layout_name) // LinearLayout mNameLayout; // // @Bind(R.id.text_name) // TextView mNameText; // // @Bind(R.id.layout_address) // LinearLayout mAddressLayout; // // @Bind(R.id.text_address) // TextView mAddressText; // // @Bind(R.id.layout_phone_number) // LinearLayout mPhoneNumberLayout; // // @Bind(R.id.text_phone_number) // TextView mPhoneNumberText; // // private static final String EXTRA_POI = // "com.hitherejoe.pickr.ui.activity.DetailActivity.EXTRA_POI"; // // private PointOfInterest mPointOfInterest; // // public static Intent getStartIntent(Context context, PointOfInterest pointOfInterest) { // Intent intent = new Intent(context, DetailActivity.class); // intent.putExtra(EXTRA_POI, pointOfInterest); // return intent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_detail); // ButterKnife.bind(this); // mPointOfInterest = getIntent().getParcelableExtra(EXTRA_POI); // if (mPointOfInterest == null) { // throw new IllegalArgumentException("DetailActivity requires a Location object!"); // } // ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment_map)).getMapAsync(this); // setupToolbar(); // setupLocationData(); // } // // @Override // public void onMapReady(final GoogleMap googleMap) { // googleMap.setMyLocationEnabled(true); // googleMap.getUiSettings().setMyLocationButtonEnabled(true); // googleMap.getUiSettings().setMapToolbarEnabled(false); // LatLng latLng = mPointOfInterest.latLng; // if (latLng != null) { // googleMap.addMarker(new MarkerOptions().position(latLng) // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); // googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f)); // } // } // // private void setupToolbar() { // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(mPointOfInterest.name); // } // } // // private void setupLocationData() { // String placeName = mPointOfInterest.name; // if (placeName != null && !placeName.isEmpty()) { // mNameText.setText(mPointOfInterest.name); // } else { // mNameLayout.setVisibility(View.GONE); // } // // String placeAddress = mPointOfInterest.address; // if (placeAddress != null && !placeAddress.isEmpty()) { // mAddressText.setText(placeAddress); // } else { // mAddressLayout.setVisibility(View.GONE); // } // // String placePhoneNumber = mPointOfInterest.phoneNumber; // if (placePhoneNumber != null && !placePhoneNumber.isEmpty()) { // mPhoneNumberText.setText(placePhoneNumber); // } else { // mPhoneNumberLayout.setVisibility(View.GONE); // } // } // // } // // Path: app/src/androidTest/java/com/hitherejoe/pickr/injection/TestComponentRule.java // public class TestComponentRule implements TestRule { // // private TestComponent mTestComponent; // // public TestDataManager getDataManager() { // return (TestDataManager) mTestComponent.dataManager(); // } // // public DatabaseHelper getDatabaseHelper() { // return getDataManager().getDatabaseHelper(); // } // // private void setupDaggerTestComponentInApplication() { // PickrApplication application = PickrApplication // .get(InstrumentationRegistry.getTargetContext()); // if (application.getComponent() instanceof TestComponent) { // mTestComponent = (TestComponent) application.getComponent(); // } else { // mTestComponent = DaggerTestComponent.builder() // .applicationTestModule(new ApplicationTestModule(application)) // .build(); // application.setComponent(mTestComponent); // } // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setupDaggerTestComponentInApplication(); // base.evaluate(); // } finally { // mTestComponent = null; // } // } // }; // } // } // Path: app/src/androidTest/java/com/hitherejoe/pickr/DetailActivityTest.java import android.content.Context; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.hitherejoe.pickr.ui.activity.DetailActivity; import com.hitherejoe.pickr.injection.TestComponentRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.InstrumentationRegistry.getTargetContext; package com.hitherejoe.pickr; @RunWith(AndroidJUnit4.class) public class DetailActivityTest { private Context mContext; @Rule public final ActivityTestRule<DetailActivity> main = new ActivityTestRule<>(DetailActivity.class, false, false); @Rule
public final TestComponentRule component = new TestComponentRule();
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/injection/module/DataManagerModule.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java // public class DatabaseHelper { // // private BriteDatabase mBriteDb; // // public DatabaseHelper(Context context) { // mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); // } // // public BriteDatabase getBriteDb() { // return mBriteDb; // } // // public Observable<PointOfInterest> saveLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.insert(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.toContentValues(pointOfInterest)); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.delete(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.COLUMN_ID + "=?", pointOfInterest.id); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> getLocation(final String id) { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME + // " WHERE " + Db.PointOfInterestTable.COLUMN_ID + "=?", id) // .map(new Func1<SqlBrite.Query, PointOfInterest>() { // @Override // public PointOfInterest call(SqlBrite.Query query) { // PointOfInterest result = null; // Cursor cursor = query.run(); // if (cursor.moveToFirst()) { // PointOfInterest pointOfInterest = // Db.PointOfInterestTable.parseCursor(cursor); // if (pointOfInterest.id.equals(id)) result = pointOfInterest; // } // cursor.close(); // return result; // } // }); // } // // public Observable<List<PointOfInterest>> getLocations() { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME) // .map(new Func1<SqlBrite.Query, List<PointOfInterest>>() { // @Override // public List<PointOfInterest> call(SqlBrite.Query query) { // Cursor cursor = query.run(); // List<PointOfInterest> result = new ArrayList<>(); // while (cursor.moveToNext()) { // result.add(Db.PointOfInterestTable.parseCursor(cursor)); // } // cursor.close(); // return result; // } // }); // } // // public Observable<Void> clearTables() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // mBriteDb.beginTransaction(); // try { // Cursor cursor = // mBriteDb.query("SELECT name FROM sqlite_master WHERE type='table'"); // while (cursor.moveToNext()) { // mBriteDb.delete(cursor.getString(cursor.getColumnIndex("name")), null); // } // cursor.close(); // mBriteDb.setTransactionSuccessful(); // subscriber.onCompleted(); // } finally { // mBriteDb.endTransaction(); // } // } // }); // } // // }
import android.content.Context; import com.hitherejoe.pickr.data.local.DatabaseHelper; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers;
package com.hitherejoe.pickr.injection.module; /** * Provide dependencies to the DataManager, mainly Helper classes and Retrofit services. */ @Module public class DataManagerModule { private final Context mContext; public DataManagerModule(Context context) { mContext = context; } @Provides @PerDataManager
// Path: app/src/main/java/com/hitherejoe/pickr/data/local/DatabaseHelper.java // public class DatabaseHelper { // // private BriteDatabase mBriteDb; // // public DatabaseHelper(Context context) { // mBriteDb = SqlBrite.create().wrapDatabaseHelper(new DbOpenHelper(context)); // } // // public BriteDatabase getBriteDb() { // return mBriteDb; // } // // public Observable<PointOfInterest> saveLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.insert(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.toContentValues(pointOfInterest)); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(final PointOfInterest pointOfInterest) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(Subscriber<? super PointOfInterest> subscriber) { // mBriteDb.delete(Db.PointOfInterestTable.TABLE_NAME, // Db.PointOfInterestTable.COLUMN_ID + "=?", pointOfInterest.id); // subscriber.onNext(pointOfInterest); // subscriber.onCompleted(); // } // }); // } // // public Observable<PointOfInterest> getLocation(final String id) { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME + // " WHERE " + Db.PointOfInterestTable.COLUMN_ID + "=?", id) // .map(new Func1<SqlBrite.Query, PointOfInterest>() { // @Override // public PointOfInterest call(SqlBrite.Query query) { // PointOfInterest result = null; // Cursor cursor = query.run(); // if (cursor.moveToFirst()) { // PointOfInterest pointOfInterest = // Db.PointOfInterestTable.parseCursor(cursor); // if (pointOfInterest.id.equals(id)) result = pointOfInterest; // } // cursor.close(); // return result; // } // }); // } // // public Observable<List<PointOfInterest>> getLocations() { // return mBriteDb.createQuery(Db.PointOfInterestTable.TABLE_NAME, // "SELECT * FROM " + Db.PointOfInterestTable.TABLE_NAME) // .map(new Func1<SqlBrite.Query, List<PointOfInterest>>() { // @Override // public List<PointOfInterest> call(SqlBrite.Query query) { // Cursor cursor = query.run(); // List<PointOfInterest> result = new ArrayList<>(); // while (cursor.moveToNext()) { // result.add(Db.PointOfInterestTable.parseCursor(cursor)); // } // cursor.close(); // return result; // } // }); // } // // public Observable<Void> clearTables() { // return Observable.create(new Observable.OnSubscribe<Void>() { // @Override // public void call(Subscriber<? super Void> subscriber) { // mBriteDb.beginTransaction(); // try { // Cursor cursor = // mBriteDb.query("SELECT name FROM sqlite_master WHERE type='table'"); // while (cursor.moveToNext()) { // mBriteDb.delete(cursor.getString(cursor.getColumnIndex("name")), null); // } // cursor.close(); // mBriteDb.setTransactionSuccessful(); // subscriber.onCompleted(); // } finally { // mBriteDb.endTransaction(); // } // } // }); // } // // } // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/DataManagerModule.java import android.content.Context; import com.hitherejoe.pickr.data.local.DatabaseHelper; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; package com.hitherejoe.pickr.injection.module; /** * Provide dependencies to the DataManager, mainly Helper classes and Retrofit services. */ @Module public class DataManagerModule { private final Context mContext; public DataManagerModule(Context context) { mContext = context; } @Provides @PerDataManager
DatabaseHelper provideDatabaseHelper() {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/util/MockModelsUtil.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // }
import com.google.android.gms.maps.model.LatLng; import com.hitherejoe.pickr.data.model.PointOfInterest; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID;
package com.hitherejoe.pickr.util; public class MockModelsUtil { public static String generateRandomString() { return UUID.randomUUID().toString(); }
// Path: app/src/main/java/com/hitherejoe/pickr/data/model/PointOfInterest.java // public class PointOfInterest implements Parcelable, Comparable<PointOfInterest> { // // public String id; // public String name; // public String address; // public LatLng latLng; // public String phoneNumber; // public LatLngBounds latLngBounds; // // public static PointOfInterest fromPlace(Place place) { // PointOfInterest pointOfInterest = new PointOfInterest(); // pointOfInterest.id = place.getId(); // pointOfInterest.name = place.getName().toString(); // pointOfInterest.address = place.getAddress().toString(); // pointOfInterest.latLng = place.getLatLng(); // pointOfInterest.phoneNumber = place.getPhoneNumber().toString(); // pointOfInterest.latLngBounds = place.getViewport(); // return pointOfInterest; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.id); // dest.writeString(this.name); // dest.writeString(this.address); // dest.writeParcelable(this.latLng, 0); // dest.writeString(this.phoneNumber); // dest.writeParcelable(this.latLngBounds, 0); // } // // public PointOfInterest() { } // // protected PointOfInterest(Parcel in) { // this.id = in.readString(); // this.name = in.readString(); // this.address = in.readString(); // this.latLng = in.readParcelable(LatLng.class.getClassLoader()); // this.phoneNumber = in.readString(); // this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); // } // // public static final Parcelable.Creator<PointOfInterest> CREATOR = new Parcelable.Creator<PointOfInterest>() { // public PointOfInterest createFromParcel(Parcel source) { // return new PointOfInterest(source); // } // // public PointOfInterest[] newArray(int size) { // return new PointOfInterest[size]; // } // }; // // @Override // public int compareTo(PointOfInterest pointOfInterest) { // return name.compareToIgnoreCase(pointOfInterest.name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // PointOfInterest that = (PointOfInterest) o; // // if (id != null ? !id.equals(that.id) : that.id != null) return false; // if (name != null ? !name.equals(that.name) : that.name != null) return false; // if (address != null ? !address.equals(that.address) : that.address != null) return false; // if (latLng != null ? !latLng.equals(that.latLng) : that.latLng != null) return false; // if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) // return false; // return !(latLngBounds != null ? !latLngBounds.equals(that.latLngBounds) : that.latLngBounds != null); // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (latLng != null ? latLng.hashCode() : 0); // result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); // result = 31 * result + (latLngBounds != null ? latLngBounds.hashCode() : 0); // return result; // } // } // Path: app/src/main/java/com/hitherejoe/pickr/util/MockModelsUtil.java import com.google.android.gms.maps.model.LatLng; import com.hitherejoe.pickr.data.model.PointOfInterest; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; package com.hitherejoe.pickr.util; public class MockModelsUtil { public static String generateRandomString() { return UUID.randomUUID().toString(); }
public static PointOfInterest createMockPointOfInterest() {
hitherejoe/Pickr
app/src/main/java/com/hitherejoe/pickr/injection/component/DataManagerComponent.java
// Path: app/src/main/java/com/hitherejoe/pickr/data/DataManager.java // public class DataManager { // // @Inject protected DatabaseHelper mDatabaseHelper; // @Inject protected Scheduler mSubscribeScheduler; // @Inject protected Bus mEventBus; // // public DataManager(Context context) { // injectDependencies(context); // } // // /* This constructor is provided so we can set up a DataManager with mocks from unit test. // * At the moment this is not possible to do with Dagger because the Gradle APT plugin doesn't // * work for the unit test variant, plus Dagger 2 doesn't provide a nice way of overriding // * modules */ // public DataManager(DatabaseHelper databaseHelper, // Bus eventBus, // Scheduler subscribeScheduler) { // mDatabaseHelper = databaseHelper; // mEventBus = eventBus; // mSubscribeScheduler = subscribeScheduler; // } // // protected void injectDependencies(Context context) { // DaggerDataManagerComponent.builder() // .applicationComponent(PickrApplication.get(context).getComponent()) // .dataManagerModule(new DataManagerModule(context)) // .build() // .inject(this); // } // // public Scheduler getScheduler() { // return mSubscribeScheduler; // } // // public Observable<List<PointOfInterest>> getLocations() { // return mDatabaseHelper.getLocations(); // } // // public Observable<PointOfInterest> saveLocation(final Context context, final PointOfInterest pointOfInterest) { // // return doesLocationExist(pointOfInterest.id).flatMap(new Func1<Boolean, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(Boolean doesLocationExist) { // if (doesLocationExist) return Observable.just(null); // // return mDatabaseHelper.saveLocation(pointOfInterest).doOnCompleted(new Action0() { // @Override // public void call() { // postEventSafely(context, new BusEvent.PlaceAdded()); // } // }); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(PointOfInterest pointOfInterest) { // return mDatabaseHelper.deleteLocation(pointOfInterest); // } // // public Observable<PlacePrediction> getAutocompleteResults(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return Observable.create(new Observable.OnSubscribe<PlacePrediction>() { // @Override // public void call(Subscriber<? super PlacePrediction> subscriber) { // // PendingResult<AutocompletePredictionBuffer> results = // Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query, // bounds, null); // // AutocompletePredictionBuffer autocompletePredictions = results // .await(60, TimeUnit.SECONDS); // // final Status status = autocompletePredictions.getStatus(); // if (!status.isSuccess()) { // autocompletePredictions.release(); // subscriber.onError(null); // } else { // for (AutocompletePrediction autocompletePrediction : autocompletePredictions) { // subscriber.onNext( // new PlacePrediction( // autocompletePrediction.getPlaceId(), // autocompletePrediction.getDescription() // )); // } // autocompletePredictions.release(); // subscriber.onCompleted(); // } // } // }); // } // // public Observable<Boolean> doesLocationExist(String id) { // return mDatabaseHelper.getLocation(id).flatMap(new Func1<PointOfInterest, Observable<Boolean>>() { // @Override // public Observable<Boolean> call(PointOfInterest pointOfInterest) { // return Observable.just(pointOfInterest != null); // } // }); // } // // public Observable<PointOfInterest> getPredictions(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return getAutocompleteResults(mGoogleApiClient, query, bounds) // .flatMap(new Func1<PlacePrediction, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(PlacePrediction placePrediction) { // return getCompleteResult(mGoogleApiClient, placePrediction.placeId.toString()); // } // }); // } // // public Observable<PointOfInterest> getCompleteResult(final GoogleApiClient mGoogleApiClient, final String id) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(final Subscriber<? super PointOfInterest> subscriber) { // final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi // .getPlaceById(mGoogleApiClient, id); // placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { // @Override // public void onResult(PlaceBuffer places) { // if (!places.getStatus().isSuccess()) { // places.release(); // subscriber.onError(null); // } else { // subscriber.onNext(PointOfInterest.fromPlace(places.get(0))); // places.close(); // subscriber.onCompleted(); // } // } // }); // } // }); // } // // private void postEventSafely(final Context context, final Object event) { // new Handler(Looper.getMainLooper()).post(new Runnable() { // @Override // public void run() { // PickrApplication.get(context).getComponent().eventBus().post(event); // } // }); // } // // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/DataManagerModule.java // @Module // public class DataManagerModule { // // private final Context mContext; // // public DataManagerModule(Context context) { // mContext = context; // } // // @Provides // @PerDataManager // DatabaseHelper provideDatabaseHelper() { // return new DatabaseHelper(mContext); // } // // @Provides // @PerDataManager // Scheduler provideSubscribeScheduler() { // return Schedulers.io(); // } // }
import com.hitherejoe.pickr.data.DataManager; import com.hitherejoe.pickr.injection.module.DataManagerModule; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Component;
package com.hitherejoe.pickr.injection.component; @PerDataManager @Component(dependencies = ApplicationComponent.class, modules = DataManagerModule.class) public interface DataManagerComponent {
// Path: app/src/main/java/com/hitherejoe/pickr/data/DataManager.java // public class DataManager { // // @Inject protected DatabaseHelper mDatabaseHelper; // @Inject protected Scheduler mSubscribeScheduler; // @Inject protected Bus mEventBus; // // public DataManager(Context context) { // injectDependencies(context); // } // // /* This constructor is provided so we can set up a DataManager with mocks from unit test. // * At the moment this is not possible to do with Dagger because the Gradle APT plugin doesn't // * work for the unit test variant, plus Dagger 2 doesn't provide a nice way of overriding // * modules */ // public DataManager(DatabaseHelper databaseHelper, // Bus eventBus, // Scheduler subscribeScheduler) { // mDatabaseHelper = databaseHelper; // mEventBus = eventBus; // mSubscribeScheduler = subscribeScheduler; // } // // protected void injectDependencies(Context context) { // DaggerDataManagerComponent.builder() // .applicationComponent(PickrApplication.get(context).getComponent()) // .dataManagerModule(new DataManagerModule(context)) // .build() // .inject(this); // } // // public Scheduler getScheduler() { // return mSubscribeScheduler; // } // // public Observable<List<PointOfInterest>> getLocations() { // return mDatabaseHelper.getLocations(); // } // // public Observable<PointOfInterest> saveLocation(final Context context, final PointOfInterest pointOfInterest) { // // return doesLocationExist(pointOfInterest.id).flatMap(new Func1<Boolean, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(Boolean doesLocationExist) { // if (doesLocationExist) return Observable.just(null); // // return mDatabaseHelper.saveLocation(pointOfInterest).doOnCompleted(new Action0() { // @Override // public void call() { // postEventSafely(context, new BusEvent.PlaceAdded()); // } // }); // } // }); // } // // public Observable<PointOfInterest> deleteLocation(PointOfInterest pointOfInterest) { // return mDatabaseHelper.deleteLocation(pointOfInterest); // } // // public Observable<PlacePrediction> getAutocompleteResults(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return Observable.create(new Observable.OnSubscribe<PlacePrediction>() { // @Override // public void call(Subscriber<? super PlacePrediction> subscriber) { // // PendingResult<AutocompletePredictionBuffer> results = // Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query, // bounds, null); // // AutocompletePredictionBuffer autocompletePredictions = results // .await(60, TimeUnit.SECONDS); // // final Status status = autocompletePredictions.getStatus(); // if (!status.isSuccess()) { // autocompletePredictions.release(); // subscriber.onError(null); // } else { // for (AutocompletePrediction autocompletePrediction : autocompletePredictions) { // subscriber.onNext( // new PlacePrediction( // autocompletePrediction.getPlaceId(), // autocompletePrediction.getDescription() // )); // } // autocompletePredictions.release(); // subscriber.onCompleted(); // } // } // }); // } // // public Observable<Boolean> doesLocationExist(String id) { // return mDatabaseHelper.getLocation(id).flatMap(new Func1<PointOfInterest, Observable<Boolean>>() { // @Override // public Observable<Boolean> call(PointOfInterest pointOfInterest) { // return Observable.just(pointOfInterest != null); // } // }); // } // // public Observable<PointOfInterest> getPredictions(final GoogleApiClient mGoogleApiClient, final String query, final LatLngBounds bounds) { // return getAutocompleteResults(mGoogleApiClient, query, bounds) // .flatMap(new Func1<PlacePrediction, Observable<PointOfInterest>>() { // @Override // public Observable<PointOfInterest> call(PlacePrediction placePrediction) { // return getCompleteResult(mGoogleApiClient, placePrediction.placeId.toString()); // } // }); // } // // public Observable<PointOfInterest> getCompleteResult(final GoogleApiClient mGoogleApiClient, final String id) { // return Observable.create(new Observable.OnSubscribe<PointOfInterest>() { // @Override // public void call(final Subscriber<? super PointOfInterest> subscriber) { // final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi // .getPlaceById(mGoogleApiClient, id); // placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { // @Override // public void onResult(PlaceBuffer places) { // if (!places.getStatus().isSuccess()) { // places.release(); // subscriber.onError(null); // } else { // subscriber.onNext(PointOfInterest.fromPlace(places.get(0))); // places.close(); // subscriber.onCompleted(); // } // } // }); // } // }); // } // // private void postEventSafely(final Context context, final Object event) { // new Handler(Looper.getMainLooper()).post(new Runnable() { // @Override // public void run() { // PickrApplication.get(context).getComponent().eventBus().post(event); // } // }); // } // // } // // Path: app/src/main/java/com/hitherejoe/pickr/injection/module/DataManagerModule.java // @Module // public class DataManagerModule { // // private final Context mContext; // // public DataManagerModule(Context context) { // mContext = context; // } // // @Provides // @PerDataManager // DatabaseHelper provideDatabaseHelper() { // return new DatabaseHelper(mContext); // } // // @Provides // @PerDataManager // Scheduler provideSubscribeScheduler() { // return Schedulers.io(); // } // } // Path: app/src/main/java/com/hitherejoe/pickr/injection/component/DataManagerComponent.java import com.hitherejoe.pickr.data.DataManager; import com.hitherejoe.pickr.injection.module.DataManagerModule; import com.hitherejoe.pickr.injection.scope.PerDataManager; import dagger.Component; package com.hitherejoe.pickr.injection.component; @PerDataManager @Component(dependencies = ApplicationComponent.class, modules = DataManagerModule.class) public interface DataManagerComponent {
void inject(DataManager dataManager);
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/transmission/impl/EventBatcherTest.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import java.util.List; import java.util.function.Consumer; import static java.time.Instant.now; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package org.zalando.nakadiproducer.transmission.impl; public class EventBatcherTest { private final ObjectMapper objectMapper = mock(ObjectMapper.class);
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/transmission/impl/EventBatcherTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import java.util.List; import java.util.function.Consumer; import static java.time.Instant.now; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package org.zalando.nakadiproducer.transmission.impl; public class EventBatcherTest { private final ObjectMapper objectMapper = mock(ObjectMapper.class);
private final Consumer<List<BatchItem>> publisher = mock(Consumer.class);
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/transmission/impl/EventBatcherTest.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import java.util.List; import java.util.function.Consumer; import static java.time.Instant.now; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package org.zalando.nakadiproducer.transmission.impl; public class EventBatcherTest { private final ObjectMapper objectMapper = mock(ObjectMapper.class); private final Consumer<List<BatchItem>> publisher = mock(Consumer.class); private EventBatcher eventBatcher = new EventBatcher(objectMapper, publisher); @Test public void shouldNotPublishEmptyBatches() { eventBatcher.finish(); verify(publisher, never()).accept(any()); } @Test public void shouldPublishNonFilledBatchOnFinish() throws JsonProcessingException {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/transmission/impl/EventBatcherTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import java.util.List; import java.util.function.Consumer; import static java.time.Instant.now; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package org.zalando.nakadiproducer.transmission.impl; public class EventBatcherTest { private final ObjectMapper objectMapper = mock(ObjectMapper.class); private final Consumer<List<BatchItem>> publisher = mock(Consumer.class); private EventBatcher eventBatcher = new EventBatcher(objectMapper, publisher); @Test public void shouldNotPublishEmptyBatches() { eventBatcher.finish(); verify(publisher, never()).accept(any()); } @Test public void shouldPublishNonFilledBatchOnFinish() throws JsonProcessingException {
EventLog eventLogEntry = eventLogEntry(1, "type");
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/MockNakadiClientConfig.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient;
package org.zalando.nakadiproducer.config; @Configuration public class MockNakadiClientConfig { @Bean
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/MockNakadiClientConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; package org.zalando.nakadiproducer.config; @Configuration public class MockNakadiClientConfig { @Bean
public NakadiPublishingClient nakadiClient() {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/MockNakadiClientConfig.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient;
package org.zalando.nakadiproducer.config; @Configuration public class MockNakadiClientConfig { @Bean public NakadiPublishingClient nakadiClient() {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/MockNakadiClientConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; package org.zalando.nakadiproducer.config; @Configuration public class MockNakadiClientConfig { @Bean public NakadiPublishingClient nakadiClient() {
return new MockNakadiPublishingClient();
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerationWebEndpointIT.java
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/TestApplication.java // @SpringBootApplication // @EnableNakadiProducer // public class TestApplication { // // public static void main(final String[] args) { // SpringApplication.run(TestApplication.class, args); // } // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // }
import static com.jayway.restassured.RestAssured.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.TestApplication; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig;
package org.zalando.nakadiproducer.snapshots; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "management.security.enabled=false", "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "management.endpoints.web.exposure.include:snapshot-event-creation" },
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/TestApplication.java // @SpringBootApplication // @EnableNakadiProducer // public class TestApplication { // // public static void main(final String[] args) { // SpringApplication.run(TestApplication.class, args); // } // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerationWebEndpointIT.java import static com.jayway.restassured.RestAssured.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.TestApplication; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig; package org.zalando.nakadiproducer.snapshots; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "management.security.enabled=false", "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "management.endpoints.web.exposure.include:snapshot-event-creation" },
classes = { TestApplication.class, EmbeddedDataSourceConfig.class, SnapshotEventGenerationWebEndpointIT.Config.class }
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerationWebEndpointIT.java
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/TestApplication.java // @SpringBootApplication // @EnableNakadiProducer // public class TestApplication { // // public static void main(final String[] args) { // SpringApplication.run(TestApplication.class, args); // } // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // }
import static com.jayway.restassured.RestAssured.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.TestApplication; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig;
package org.zalando.nakadiproducer.snapshots; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "management.security.enabled=false", "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "management.endpoints.web.exposure.include:snapshot-event-creation" },
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/TestApplication.java // @SpringBootApplication // @EnableNakadiProducer // public class TestApplication { // // public static void main(final String[] args) { // SpringApplication.run(TestApplication.class, args); // } // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerationWebEndpointIT.java import static com.jayway.restassured.RestAssured.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.TestApplication; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig; package org.zalando.nakadiproducer.snapshots; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "management.security.enabled=false", "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "management.endpoints.web.exposure.include:snapshot-event-creation" },
classes = { TestApplication.class, EmbeddedDataSourceConfig.class, SnapshotEventGenerationWebEndpointIT.Config.class }
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/MockNakadiConfig.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient;
package org.zalando.nakadiproducer.tests; @Configuration public class MockNakadiConfig { @Bean
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // Path: nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/MockNakadiConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; package org.zalando.nakadiproducer.tests; @Configuration public class MockNakadiConfig { @Bean
public NakadiPublishingClient mockNakadiPublishingClient() {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/MockNakadiConfig.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient;
package org.zalando.nakadiproducer.tests; @Configuration public class MockNakadiConfig { @Bean public NakadiPublishingClient mockNakadiPublishingClient() {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // Path: nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/MockNakadiConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; package org.zalando.nakadiproducer.tests; @Configuration public class MockNakadiConfig { @Bean public NakadiPublishingClient mockNakadiPublishingClient() {
return new MockNakadiPublishingClient();
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGeneratorAutoconfigurationIT.java
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/BaseMockedExternalCommunicationIT.java // @ActiveProfiles("test") // @RunWith(SpringRunner.class) // @SpringBootTest( // webEnvironment = SpringBootTest.WebEnvironment.MOCK, // properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false" }, // classes = { TestApplication.class, EmbeddedDataSourceConfig.class } // ) // public abstract class BaseMockedExternalCommunicationIT { // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/impl/SnapshotCreationService.java // public class SnapshotCreationService { // // private final Map<String, SnapshotEventGenerator> snapshotEventProviders; // // private final EventLogWriter eventLogWriter; // // /** // * Creates the service. // * // * @param snapshotEventGenerators // * the event generators. Each of them must have a different // * supported event type. // * @param eventLogWriter // * The event log writer to which the newly generated snapshot // * events are pushed. // * @throws IllegalStateException if two event generators declare to be responsible for the same event type. // */ // public SnapshotCreationService(List<SnapshotEventGenerator> snapshotEventGenerators, // EventLogWriter eventLogWriter) { // this.snapshotEventProviders = snapshotEventGenerators.stream() // .collect(toMap(SnapshotEventGenerator::getSupportedEventType, identity())); // this.eventLogWriter = eventLogWriter; // } // // public void createSnapshotEvents(final String eventType, String filter) { // final SnapshotEventGenerator snapshotEventGenerator = snapshotEventProviders.get(eventType); // if (snapshotEventGenerator == null) { // throw new UnknownEventTypeException(eventType); // } // // Object lastProcessedId = null; // do { // final List<Snapshot> snapshots = snapshotEventGenerator.generateSnapshots(lastProcessedId, filter); // if (snapshots.isEmpty()) { // break; // } // // for (final Snapshot snapshot : snapshots) { // eventLogWriter.fireSnapshotEvent(eventType, snapshot.getDataType(), snapshot.getData()); // lastProcessedId = snapshot.getId(); // } // } while (true); // } // // public Set<String> getSupportedEventTypes() { // return unmodifiableSet(snapshotEventProviders.keySet()); // } // }
import static org.junit.Assert.fail; import java.util.Collections; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.zalando.nakadiproducer.BaseMockedExternalCommunicationIT; import org.zalando.nakadiproducer.snapshots.impl.SnapshotCreationService;
package org.zalando.nakadiproducer.snapshots; @ContextConfiguration(classes=SnapshotEventGeneratorAutoconfigurationIT.Config.class) public class SnapshotEventGeneratorAutoconfigurationIT extends BaseMockedExternalCommunicationIT { @Autowired
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/BaseMockedExternalCommunicationIT.java // @ActiveProfiles("test") // @RunWith(SpringRunner.class) // @SpringBootTest( // webEnvironment = SpringBootTest.WebEnvironment.MOCK, // properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false" }, // classes = { TestApplication.class, EmbeddedDataSourceConfig.class } // ) // public abstract class BaseMockedExternalCommunicationIT { // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/impl/SnapshotCreationService.java // public class SnapshotCreationService { // // private final Map<String, SnapshotEventGenerator> snapshotEventProviders; // // private final EventLogWriter eventLogWriter; // // /** // * Creates the service. // * // * @param snapshotEventGenerators // * the event generators. Each of them must have a different // * supported event type. // * @param eventLogWriter // * The event log writer to which the newly generated snapshot // * events are pushed. // * @throws IllegalStateException if two event generators declare to be responsible for the same event type. // */ // public SnapshotCreationService(List<SnapshotEventGenerator> snapshotEventGenerators, // EventLogWriter eventLogWriter) { // this.snapshotEventProviders = snapshotEventGenerators.stream() // .collect(toMap(SnapshotEventGenerator::getSupportedEventType, identity())); // this.eventLogWriter = eventLogWriter; // } // // public void createSnapshotEvents(final String eventType, String filter) { // final SnapshotEventGenerator snapshotEventGenerator = snapshotEventProviders.get(eventType); // if (snapshotEventGenerator == null) { // throw new UnknownEventTypeException(eventType); // } // // Object lastProcessedId = null; // do { // final List<Snapshot> snapshots = snapshotEventGenerator.generateSnapshots(lastProcessedId, filter); // if (snapshots.isEmpty()) { // break; // } // // for (final Snapshot snapshot : snapshots) { // eventLogWriter.fireSnapshotEvent(eventType, snapshot.getDataType(), snapshot.getData()); // lastProcessedId = snapshot.getId(); // } // } while (true); // } // // public Set<String> getSupportedEventTypes() { // return unmodifiableSet(snapshotEventProviders.keySet()); // } // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGeneratorAutoconfigurationIT.java import static org.junit.Assert.fail; import java.util.Collections; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.zalando.nakadiproducer.BaseMockedExternalCommunicationIT; import org.zalando.nakadiproducer.snapshots.impl.SnapshotCreationService; package org.zalando.nakadiproducer.snapshots; @ContextConfiguration(classes=SnapshotEventGeneratorAutoconfigurationIT.Config.class) public class SnapshotEventGeneratorAutoconfigurationIT extends BaseMockedExternalCommunicationIT { @Autowired
private SnapshotCreationService snapshotCreationService;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterImpl.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/EventLogWriter.java // public interface EventLogWriter { // // /** // * Fires a data change event about a <b>creation</b> of some resource // * (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the // * resource which was created. It will be used as content of the // * {@code data} field of the Nakadi event. // */ // @Transactional // void fireCreateEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event about an update of some resource (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the new // * state of the resource which was updated. It will be used as // * content of the {@code data} field of the Nakadi event. // */ // @Transactional // void fireUpdateEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event about the deletion of some resource (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the last // * state (before the deletion) of the resource which was deleted. // * It will be used as content of the {@code data} field of the // * Nakadi event. // */ // @Transactional // void fireDeleteEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event with a snapshot of some resource (object). // * <p> // * This notifies your consumers about the current state of a resource, even // * if nothing changed. Typical use cases include initial replication to new // * consumers or hotfixes of data inconsistencies between producer and // * consumer. // * </p> // * <p> // * Normally applications don't have to call this themselves, instead they // * should implement the // * {@link SnapshotEventGenerator} // * interface to add support for snapshot creation via the actuator endpoint. // * </p> // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the // * current state of the resource. It will be used as content of // * the {@code data} field of the Nakadi event. // */ // @Transactional // void fireSnapshotEvent(String eventType, String dataType, Object data); // // /** // * Fires a business event, i.e. an event communicating the fact that some // * business process step happened. The payload object will be used as the // * main event content (just metadata will be added). Same as for data change // * events, you should call this method in the same transaction as you are // * storing related changes into your database. // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param payload // * some POJO that can be serialized into JSON (required // * parameter) // */ // @Transactional // void fireBusinessEvent(String eventType, Object payload); // }
import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.CREATE; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.DELETE; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.SNAPSHOT; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.UPDATE; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.eventlog.EventLogWriter; import javax.transaction.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper;
package org.zalando.nakadiproducer.eventlog.impl; public class EventLogWriterImpl implements EventLogWriter { private final EventLogRepository eventLogRepository; private final ObjectMapper objectMapper;
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/EventLogWriter.java // public interface EventLogWriter { // // /** // * Fires a data change event about a <b>creation</b> of some resource // * (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the // * resource which was created. It will be used as content of the // * {@code data} field of the Nakadi event. // */ // @Transactional // void fireCreateEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event about an update of some resource (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the new // * state of the resource which was updated. It will be used as // * content of the {@code data} field of the Nakadi event. // */ // @Transactional // void fireUpdateEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event about the deletion of some resource (object). // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the last // * state (before the deletion) of the resource which was deleted. // * It will be used as content of the {@code data} field of the // * Nakadi event. // */ // @Transactional // void fireDeleteEvent(String eventType, String dataType, Object data); // // /** // * Fires a data change event with a snapshot of some resource (object). // * <p> // * This notifies your consumers about the current state of a resource, even // * if nothing changed. Typical use cases include initial replication to new // * consumers or hotfixes of data inconsistencies between producer and // * consumer. // * </p> // * <p> // * Normally applications don't have to call this themselves, instead they // * should implement the // * {@link SnapshotEventGenerator} // * interface to add support for snapshot creation via the actuator endpoint. // * </p> // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param dataType // * the content of the {@code data_type} field of the Nakadi // * event. // * // * @param data // * some POJO that can be serialized into JSON (required // * parameter). This is meant to be a representation of the // * current state of the resource. It will be used as content of // * the {@code data} field of the Nakadi event. // */ // @Transactional // void fireSnapshotEvent(String eventType, String dataType, Object data); // // /** // * Fires a business event, i.e. an event communicating the fact that some // * business process step happened. The payload object will be used as the // * main event content (just metadata will be added). Same as for data change // * events, you should call this method in the same transaction as you are // * storing related changes into your database. // * // * @param eventType // * the Nakadi event type of the event. This is roughly equivalent // * to an event channel or topic. // * // * @param payload // * some POJO that can be serialized into JSON (required // * parameter) // */ // @Transactional // void fireBusinessEvent(String eventType, Object payload); // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterImpl.java import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.CREATE; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.DELETE; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.SNAPSHOT; import static org.zalando.nakadiproducer.eventlog.impl.EventDataOperation.UPDATE; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.eventlog.EventLogWriter; import javax.transaction.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; package org.zalando.nakadiproducer.eventlog.impl; public class EventLogWriterImpl implements EventLogWriter { private final EventLogRepository eventLogRepository; private final ObjectMapper objectMapper;
private final FlowIdComponent flowIdComponent;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // }
import java.util.ArrayList; import java.util.List; import org.zalando.nakadiproducer.snapshots.Snapshot;
package org.zalando.nakadiproducer.util; public class Fixture { public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; public static MockPayload mockPayload(Integer id, String code, Boolean isActive, MockPayload.SubClass more, List<MockPayload.SubListItem> items) { return MockPayload.builder() .id(id) .code(code) .isActive(isActive) .more(more) .items(items) .build(); } public static MockPayload mockPayload(Integer id, String code) { return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); }
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java import java.util.ArrayList; import java.util.List; import org.zalando.nakadiproducer.snapshots.Snapshot; package org.zalando.nakadiproducer.util; public class Fixture { public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; public static MockPayload mockPayload(Integer id, String code, Boolean isActive, MockPayload.SubClass more, List<MockPayload.SubListItem> items) { return MockPayload.builder() .id(id) .code(code) .isActive(isActive) .more(more) .items(items) .build(); } public static MockPayload mockPayload(Integer id, String code) { return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); }
public static List<Snapshot> mockSnapshotList(Integer size) {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/BaseMockedExternalCommunicationIT.java
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // }
import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig;
package org.zalando.nakadiproducer; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false" },
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/BaseMockedExternalCommunicationIT.java import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig; package org.zalando.nakadiproducer; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false" },
classes = { TestApplication.class, EmbeddedDataSourceConfig.class }
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // }
import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventBatcher { private static final long NAKADI_BATCH_SIZE_LIMIT_IN_BYTES = 50000000; private final ObjectMapper objectMapper; private final Consumer<List<BatchItem>> publisher; private List<BatchItem> batch; private long aggregatedBatchSize; public EventBatcher(ObjectMapper objectMapper, Consumer<List<BatchItem>> publisher) { this.objectMapper = objectMapper; this.publisher = publisher; this.batch = new ArrayList<>(); this.aggregatedBatchSize = 0; } /** * Pushes one event to be published. It will be either published right now, or with some other events, * latest when calling {@link #finish()}. * @param eventLogEntry The event log entry for this event. * @param nakadiEvent The Nakadi form of the event. */
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventBatcher { private static final long NAKADI_BATCH_SIZE_LIMIT_IN_BYTES = 50000000; private final ObjectMapper objectMapper; private final Consumer<List<BatchItem>> publisher; private List<BatchItem> batch; private long aggregatedBatchSize; public EventBatcher(ObjectMapper objectMapper, Consumer<List<BatchItem>> publisher) { this.objectMapper = objectMapper; this.publisher = publisher; this.batch = new ArrayList<>(); this.aggregatedBatchSize = 0; } /** * Pushes one event to be published. It will be either published right now, or with some other events, * latest when calling {@link #finish()}. * @param eventLogEntry The event log entry for this event. * @param nakadiEvent The Nakadi form of the event. */
public void pushEvent(EventLog eventLogEntry, NakadiEvent nakadiEvent) {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS;
package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS; package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService {
private final EventLogRepository eventLogRepository;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS;
package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService { private final EventLogRepository eventLogRepository;
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS; package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService { private final EventLogRepository eventLogRepository;
private final NakadiPublishingClient nakadiPublishingClient;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS;
package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService { private final EventLogRepository eventLogRepository; private final NakadiPublishingClient nakadiPublishingClient; private final ObjectMapper objectMapper; private final int lockDuration; private final int lockDurationBuffer; private Clock clock = Clock.systemDefaultZone(); public EventTransmissionService(EventLogRepository eventLogRepository, NakadiPublishingClient nakadiPublishingClient, ObjectMapper objectMapper, int lockDuration, int lockDurationBuffer) { this.eventLogRepository = eventLogRepository; this.nakadiPublishingClient = nakadiPublishingClient; this.objectMapper = objectMapper; this.lockDuration = lockDuration; this.lockDurationBuffer = lockDurationBuffer; } @Transactional
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS; package org.zalando.nakadiproducer.transmission.impl; @Slf4j public class EventTransmissionService { private final EventLogRepository eventLogRepository; private final NakadiPublishingClient nakadiPublishingClient; private final ObjectMapper objectMapper; private final int lockDuration; private final int lockDurationBuffer; private Clock clock = Clock.systemDefaultZone(); public EventTransmissionService(EventLogRepository eventLogRepository, NakadiPublishingClient nakadiPublishingClient, ObjectMapper objectMapper, int lockDuration, int lockDurationBuffer) { this.eventLogRepository = eventLogRepository; this.nakadiPublishingClient = nakadiPublishingClient; this.objectMapper = objectMapper; this.lockDuration = lockDuration; this.lockDurationBuffer = lockDurationBuffer; } @Transactional
public Collection<EventLog> lockSomeEvents() {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS;
@Transactional public void sendEvents(Collection<EventLog> events) { EventBatcher batcher = new EventBatcher(objectMapper, this::publishBatch); for (EventLog event : events) { if (lockNearlyExpired(event)) { // to avoid that two instances process this event, we skip it continue; } NakadiEvent nakadiEvent; try { nakadiEvent = mapToNakadiEvent(event); } catch (Exception e) { log.error("Could not serialize event {} of type {}, skipping it.", event.getId(), event.getEventType(), e); continue; } batcher.pushEvent(event, nakadiEvent); } batcher.finish(); } /** * Publishes a list of events. * All of the events in this list need to be destined for the same event type. */
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLog.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class EventLog { // // private Integer id; // private String eventType; // private String eventBodyData; // private String flowId; // private Instant created; // private Instant lastModified; // private String lockedBy; // private Instant lockedUntil; // // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/eventlog/impl/EventLogRepository.java // public interface EventLogRepository { // Collection<EventLog> findByLockedByAndLockedUntilGreaterThan(String lockedBy, Instant lockedUntil); // // void lockSomeMessages(String lockId, Instant now, Instant lockExpires); // // void delete(EventLog eventLog); // // void persist(EventLog eventLog); // // void deleteAll(); // // EventLog findOne(Integer id); // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/NakadiPublishingClient.java // public interface NakadiPublishingClient { // void publish(String eventType, List<?> nakadiEvents) throws Exception; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventBatcher.java // @AllArgsConstructor // @Getter // @EqualsAndHashCode // @ToString // protected static class BatchItem { // EventLog eventLogEntry; // NakadiEvent nakadiEvent; // } // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmissionService.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.zalando.fahrschein.EventPublishingException; import org.zalando.fahrschein.domain.BatchItemResponse; import org.zalando.nakadiproducer.eventlog.impl.EventLog; import org.zalando.nakadiproducer.eventlog.impl.EventLogRepository; import org.zalando.nakadiproducer.transmission.NakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventBatcher.BatchItem; import javax.transaction.Transactional; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.SECONDS; @Transactional public void sendEvents(Collection<EventLog> events) { EventBatcher batcher = new EventBatcher(objectMapper, this::publishBatch); for (EventLog event : events) { if (lockNearlyExpired(event)) { // to avoid that two instances process this event, we skip it continue; } NakadiEvent nakadiEvent; try { nakadiEvent = mapToNakadiEvent(event); } catch (Exception e) { log.error("Could not serialize event {} of type {}, skipping it.", event.getId(), event.getEventType(), e); continue; } batcher.pushEvent(event, nakadiEvent); } batcher.finish(); } /** * Publishes a list of events. * All of the events in this list need to be destined for the same event type. */
private void publishBatch(List<BatchItem> batch) {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-loadtest/src/test/java/org/zalando/nakadiproducer/configuration/TokenConfiguration.java
// Path: nakadi-producer-spring-boot-starter/src/main/java/org/zalando/nakadiproducer/AccessTokenProvider.java // public interface AccessTokenProvider { // String getAccessToken(); // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.AccessTokenProvider;
package org.zalando.nakadiproducer.configuration; @Configuration public class TokenConfiguration { @Primary @Bean
// Path: nakadi-producer-spring-boot-starter/src/main/java/org/zalando/nakadiproducer/AccessTokenProvider.java // public interface AccessTokenProvider { // String getAccessToken(); // } // Path: nakadi-producer-loadtest/src/test/java/org/zalando/nakadiproducer/configuration/TokenConfiguration.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.AccessTokenProvider; package org.zalando.nakadiproducer.configuration; @Configuration public class TokenConfiguration { @Primary @Bean
public AccessTokenProvider accessTokenProvider() {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // }
import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections;
package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // } // Path: nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean
public SnapshotEventGenerator snapshotEventGenerator() {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // }
import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections;
package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean public SnapshotEventGenerator snapshotEventGenerator() {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // } // Path: nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean public SnapshotEventGenerator snapshotEventGenerator() {
return new SimpleSnapshotEventGenerator("eventtype", (withIdGreaterThan, filter) -> {
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // }
import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections;
package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean public SnapshotEventGenerator snapshotEventGenerator() { return new SimpleSnapshotEventGenerator("eventtype", (withIdGreaterThan, filter) -> { if (withIdGreaterThan == null) {
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SimpleSnapshotEventGenerator.java // public final class SimpleSnapshotEventGenerator implements SnapshotEventGenerator { // private final String supportedEventType; // private final BiFunction<Object, String, List<Snapshot>> getSnapshotFunction; // // /** // * Creates a SnapshotEventGenerator for an event type, which doesn't support // * filtering. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)} // * (but without the filter parameter). Any filter provided by the // * caller will be thrown away. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // Function<Object, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = (id, filter) -> snapshotEventFactory.apply(id); // } // // /** // * Creates a SnapshotEventGenerator for an event type, with filtering // * support. // * // * @param supportedEventType // * the eventType that this SnapShotEventProvider will support. // * @param snapshotEventFactory // * a snapshot event factory function conforming to the // * specification of // * {@link SnapshotEventGenerator#generateSnapshots(Object, String)}. // */ // public SimpleSnapshotEventGenerator(String supportedEventType, // BiFunction<Object, String, List<Snapshot>> snapshotEventFactory) { // this.supportedEventType = supportedEventType; // this.getSnapshotFunction = snapshotEventFactory; // } // // @Override // public List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter) { // return getSnapshotFunction.apply(withIdGreaterThan, filter); // } // // @Override // public String getSupportedEventType() { // return supportedEventType; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/Snapshot.java // @AllArgsConstructor // @Getter // public class Snapshot { // private Object id; // private String dataType; // private Object data; // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/snapshots/SnapshotEventGenerator.java // public interface SnapshotEventGenerator { // // /** // * <p> // * Returns a batch of snapshots of given type (event type is an event // * channel topic name). The implementation may return an arbitrary amount of // * results, but it must return at least one element if there are entities // * matching the parameters. // * </p> // * <p> // * Calling this method must have no side effects. // * </p> // * The library will call your implementation like this: // * <ul> // * <li>Request: generateSnapshots(null, filter), Response: 1,2,3</li> // * <li>Request: generateSnapshots(3, filter), Response: 4,5</li> // * <li>Request: generateSnapshots(5, filter), Response: emptyList</li> // * </ul> // * <p> // * It is your responsibility to make sure that the returned events are // * ordered by their ID ascending and that, given you return a list of events // * for entities with IDs {id<sub>1</sub>, ..., id<sub>N</sub>}, there exists // * no entity with an ID between id<sub>1</sub> and id<sub>N</sub>, that is // * not part of the result. // * </p> // * // * @param withIdGreaterThan // * if not null, only events for entities with an ID greater than // * the given one must be returned // * // * @param filter // * a filter for the snapshot generation mechanism. This value is // * simply passed through from the request body of the REST // * endpoint (or from any other triggering mechanism). If there // * was no request body, this will be {@code null}. // * // * Implementors can interpret it in whatever way they want (even // * ignore it). All calls for one snapshot generation will receive // * the same string. // * // * @return list of elements (wrapped in Snapshot objects) ordered by their // * ID. // */ // List<Snapshot> generateSnapshots(Object withIdGreaterThan, String filter); // // /** // * The name of the event type supported by this snapshot generator. // */ // String getSupportedEventType(); // } // Path: nakadi-producer-starter-spring-boot-2-test/src/main/java/org/zalando/nakadiproducer/tests/Application.java import com.opentable.db.postgres.embedded.EmbeddedPostgres; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.zalando.nakadiproducer.EnableNakadiProducer; import org.zalando.nakadiproducer.snapshots.SimpleSnapshotEventGenerator; import org.zalando.nakadiproducer.snapshots.Snapshot; import org.zalando.nakadiproducer.snapshots.SnapshotEventGenerator; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; package org.zalando.nakadiproducer.tests; @EnableAutoConfiguration @EnableNakadiProducer public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean @Primary public DataSource dataSource(EmbeddedPostgres postgres) throws IOException { return postgres.getPostgresDatabase(); } @Bean public EmbeddedPostgres embeddedPostgres() throws IOException { return EmbeddedPostgres.start(); } @Bean public SnapshotEventGenerator snapshotEventGenerator() { return new SimpleSnapshotEventGenerator("eventtype", (withIdGreaterThan, filter) -> { if (withIdGreaterThan == null) {
return Collections.singletonList(new Snapshot("1", "foo", filter));
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper;
package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper; package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock
private FlowIdComponent flowIdComponent;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper;
package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter;
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper; package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter;
private MockPayload eventPayload;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper;
package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter; private MockPayload eventPayload; private static final String TRACE_ID = "TRACE_ID"; private static final String EVENT_BODY_DATA = ("{'id':1," + "'code':'mockedcode'," + "'more':{'info':'some info'}," + "'items':[{'detail':'some detail0'},{'detail':'some detail1'}]," + "'active':true" + "}").replace('\'', '"'); private static final String DATA_CHANGE_BODY_DATA = ("{'data_op':'{DATA_OP}','data_type':'nakadi:some-publisher','data':" + EVENT_BODY_DATA + "}").replace('\'', '"'); private static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; @Before public void setUp() throws Exception {
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper; package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter; private MockPayload eventPayload; private static final String TRACE_ID = "TRACE_ID"; private static final String EVENT_BODY_DATA = ("{'id':1," + "'code':'mockedcode'," + "'more':{'info':'some info'}," + "'items':[{'detail':'some detail0'},{'detail':'some detail1'}]," + "'active':true" + "}").replace('\'', '"'); private static final String DATA_CHANGE_BODY_DATA = ("{'data_op':'{DATA_OP}','data_type':'nakadi:some-publisher','data':" + EVENT_BODY_DATA + "}").replace('\'', '"'); private static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; @Before public void setUp() throws Exception {
eventPayload = Fixture.mockPayload(1, "mockedcode", true,
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper;
package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter; private MockPayload eventPayload; private static final String TRACE_ID = "TRACE_ID"; private static final String EVENT_BODY_DATA = ("{'id':1," + "'code':'mockedcode'," + "'more':{'info':'some info'}," + "'items':[{'detail':'some detail0'},{'detail':'some detail1'}]," + "'active':true" + "}").replace('\'', '"'); private static final String DATA_CHANGE_BODY_DATA = ("{'data_op':'{DATA_OP}','data_type':'nakadi:some-publisher','data':" + EVENT_BODY_DATA + "}").replace('\'', '"'); private static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; @Before public void setUp() throws Exception { eventPayload = Fixture.mockPayload(1, "mockedcode", true, Fixture.mockSubClass("some info"), Fixture.mockSubList(2, "some detail")); when(flowIdComponent.getXFlowIdValue()).thenReturn(TRACE_ID); eventLogWriter = new EventLogWriterImpl(eventLogRepository, new ObjectMapper(), flowIdComponent); } @Test public void testFireCreateEvent() throws Exception {
// Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/util/Fixture.java // public class Fixture { // // public static final String PUBLISHER_EVENT_TYPE = "wholesale.some-publisher-change-event"; // public static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; // // public static MockPayload mockPayload(Integer id, String code, Boolean isActive, // MockPayload.SubClass more, List<MockPayload.SubListItem> items) { // return MockPayload.builder() // .id(id) // .code(code) // .isActive(isActive) // .more(more) // .items(items) // .build(); // } // // public static MockPayload mockPayload(Integer id, String code) { // return mockPayload(id, code, true, mockSubClass(), mockSubList(3)); // } // // public static List<Snapshot> mockSnapshotList(Integer size) { // final List<Snapshot> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // list.add(new Snapshot(i, PUBLISHER_DATA_TYPE, mockPayload(i + 1, "code" + i, true, // mockSubClass("some info " + i), mockSubList(3, "some detail for code" + i)))); // } // return list; // } // // public static MockPayload.SubClass mockSubClass(String info) { // return MockPayload.SubClass.builder().info(info).build(); // } // // private static MockPayload.SubClass mockSubClass() { // return mockSubClass("Info something"); // } // // private static MockPayload.SubListItem mockSubListItem(String detail) { // return MockPayload.SubListItem.builder().detail(detail).build(); // } // // public static List<MockPayload.SubListItem> mockSubList(Integer size, String detail) { // final List<MockPayload.SubListItem> items = new ArrayList<>(); // for (int i = 0; i < size; i++) { // items.add(mockSubListItem(detail + i)); // } // return items; // } // // private static List<MockPayload.SubListItem> mockSubList(Integer size) { // return mockSubList(size, "Detail something "); // } // // } // // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/util/MockPayload.java // @ToString // @Getter // @Setter // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class MockPayload { // private Integer id; // // private String code; // // @Builder.Default // private boolean isActive = true; // // private SubClass more; // // private List<SubListItem> items; // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubClass { // private String info; // } // // @Builder(toBuilder = true) // @Getter // @Setter // @ToString // @AllArgsConstructor // @NoArgsConstructor // public static class SubListItem { // private String detail; // } // } // Path: nakadi-producer/src/test/java/org/zalando/nakadiproducer/eventlog/impl/EventLogWriterTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.zalando.nakadiproducer.util.Fixture.PUBLISHER_EVENT_TYPE; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.zalando.nakadiproducer.flowid.FlowIdComponent; import org.zalando.nakadiproducer.util.Fixture; import org.zalando.nakadiproducer.util.MockPayload; import com.fasterxml.jackson.databind.ObjectMapper; package org.zalando.nakadiproducer.eventlog.impl; @RunWith(MockitoJUnitRunner.class) public class EventLogWriterTest { @Mock private EventLogRepository eventLogRepository; @Mock private FlowIdComponent flowIdComponent; @Captor private ArgumentCaptor<EventLog> eventLogCapture; private EventLogWriterImpl eventLogWriter; private MockPayload eventPayload; private static final String TRACE_ID = "TRACE_ID"; private static final String EVENT_BODY_DATA = ("{'id':1," + "'code':'mockedcode'," + "'more':{'info':'some info'}," + "'items':[{'detail':'some detail0'},{'detail':'some detail1'}]," + "'active':true" + "}").replace('\'', '"'); private static final String DATA_CHANGE_BODY_DATA = ("{'data_op':'{DATA_OP}','data_type':'nakadi:some-publisher','data':" + EVENT_BODY_DATA + "}").replace('\'', '"'); private static final String PUBLISHER_DATA_TYPE = "nakadi:some-publisher"; @Before public void setUp() throws Exception { eventPayload = Fixture.mockPayload(1, "mockedcode", true, Fixture.mockSubClass("some info"), Fixture.mockSubList(2, "some detail")); when(flowIdComponent.getXFlowIdValue()).thenReturn(TRACE_ID); eventLogWriter = new EventLogWriterImpl(eventLogRepository, new ObjectMapper(), flowIdComponent); } @Test public void testFireCreateEvent() throws Exception {
eventLogWriter.fireCreateEvent(PUBLISHER_EVENT_TYPE, PUBLISHER_DATA_TYPE, eventPayload);
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/main/java/org/zalando/nakadiproducer/snapshots/impl/SnapshotEventCreationEndpoint.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // }
import java.util.Set; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.lang.Nullable; import org.zalando.nakadiproducer.flowid.FlowIdComponent;
package org.zalando.nakadiproducer.snapshots.impl; @Endpoint(id = "snapshot-event-creation") public class SnapshotEventCreationEndpoint { private final SnapshotCreationService snapshotCreationService;
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/flowid/FlowIdComponent.java // public interface FlowIdComponent { // String getXFlowIdValue(); // // void startTraceIfNoneExists(); // } // Path: nakadi-producer-spring-boot-starter/src/main/java/org/zalando/nakadiproducer/snapshots/impl/SnapshotEventCreationEndpoint.java import java.util.Set; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.lang.Nullable; import org.zalando.nakadiproducer.flowid.FlowIdComponent; package org.zalando.nakadiproducer.snapshots.impl; @Endpoint(id = "snapshot-event-creation") public class SnapshotEventCreationEndpoint { private final SnapshotCreationService snapshotCreationService;
private final FlowIdComponent flowIdComponent;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/NonNakadiProducerFlywayCallbackIT.java
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // }
import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.sql.Connection; import org.flywaydb.core.api.callback.FlywayCallback; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig;
package org.zalando.nakadiproducer; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "spring.flyway.enabled:false"},
// Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/config/EmbeddedDataSourceConfig.java // @Configuration // public class EmbeddedDataSourceConfig { // // @Bean // @Primary // public DataSource dataSource() throws IOException { // return embeddedPostgres().getPostgresDatabase(); // } // // @Bean // public EmbeddedPostgres embeddedPostgres() throws IOException { // return EmbeddedPostgres.start(); // } // } // Path: nakadi-producer-spring-boot-starter/src/test/java/org/zalando/nakadiproducer/NonNakadiProducerFlywayCallbackIT.java import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.sql.Connection; import org.flywaydb.core.api.callback.FlywayCallback; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.config.EmbeddedDataSourceConfig; package org.zalando.nakadiproducer; @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = { "zalando.team.id:alpha-local-testing", "nakadi-producer.scheduled-transmission-enabled:false", "spring.flyway.enabled:false"},
classes = { TestApplication.class, EmbeddedDataSourceConfig.class }
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/ApplicationIT.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmitter.java // public class EventTransmitter { // private final EventTransmissionService eventTransmissionService; // // public EventTransmitter(EventTransmissionService eventTransmissionService) { // this.eventTransmissionService = eventTransmissionService; // } // // public void sendEvents() { // eventTransmissionService.sendEvents(eventTransmissionService.lockSomeEvents()); // } // }
import org.junit.*; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventTransmitter; import java.io.File; import java.util.List; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat;
package org.zalando.nakadiproducer.tests; @RunWith(SpringRunner.class) @SpringBootTest( // This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up // by our starter *even if* it has been defined *after* the application itself. This has been a problem until // this commit. classes = { Application.class, MockNakadiConfig.class }, properties = { "nakadi-producer.transmission-polling-delay=30"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) public class ApplicationIT { @LocalManagementPort private int localManagementPort; @ClassRule public static final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @BeforeClass public static void fakeCredentialsDir() { environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath()); } @Autowired
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmitter.java // public class EventTransmitter { // private final EventTransmissionService eventTransmissionService; // // public EventTransmitter(EventTransmissionService eventTransmissionService) { // this.eventTransmissionService = eventTransmissionService; // } // // public void sendEvents() { // eventTransmissionService.sendEvents(eventTransmissionService.lockSomeEvents()); // } // } // Path: nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/ApplicationIT.java import org.junit.*; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventTransmitter; import java.io.File; import java.util.List; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; package org.zalando.nakadiproducer.tests; @RunWith(SpringRunner.class) @SpringBootTest( // This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up // by our starter *even if* it has been defined *after* the application itself. This has been a problem until // this commit. classes = { Application.class, MockNakadiConfig.class }, properties = { "nakadi-producer.transmission-polling-delay=30"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) public class ApplicationIT { @LocalManagementPort private int localManagementPort; @ClassRule public static final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @BeforeClass public static void fakeCredentialsDir() { environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath()); } @Autowired
private MockNakadiPublishingClient mockClient;
zalando-nakadi/nakadi-producer-spring-boot-starter
nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/ApplicationIT.java
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmitter.java // public class EventTransmitter { // private final EventTransmissionService eventTransmissionService; // // public EventTransmitter(EventTransmissionService eventTransmissionService) { // this.eventTransmissionService = eventTransmissionService; // } // // public void sendEvents() { // eventTransmissionService.sendEvents(eventTransmissionService.lockSomeEvents()); // } // }
import org.junit.*; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventTransmitter; import java.io.File; import java.util.List; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat;
package org.zalando.nakadiproducer.tests; @RunWith(SpringRunner.class) @SpringBootTest( // This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up // by our starter *even if* it has been defined *after* the application itself. This has been a problem until // this commit. classes = { Application.class, MockNakadiConfig.class }, properties = { "nakadi-producer.transmission-polling-delay=30"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) public class ApplicationIT { @LocalManagementPort private int localManagementPort; @ClassRule public static final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @BeforeClass public static void fakeCredentialsDir() { environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath()); } @Autowired private MockNakadiPublishingClient mockClient; @Autowired
// Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/MockNakadiPublishingClient.java // public class MockNakadiPublishingClient implements NakadiPublishingClient { // private final ObjectMapper objectMapper; // private final MultiValueMap<String, String> sentEvents = new LinkedMultiValueMap<>(); // // public MockNakadiPublishingClient() { // this(createDefaultObjectMapper()); // } // // public MockNakadiPublishingClient(ObjectMapper objectMapper) { // this.objectMapper = objectMapper; // } // // @Override // public synchronized void publish(String eventType, List<?> nakadiEvents) throws Exception { // nakadiEvents.stream().map(this::transformToJson).forEach(e -> sentEvents.add(eventType, e)); // } // // public synchronized List<String> getSentEvents(String eventType) { // ArrayList<String> events = new ArrayList<>(); // List<String> sentEvents = this.sentEvents.get(eventType); // if (sentEvents != null) { // events.addAll(sentEvents); // } // return events; // } // // public synchronized void clearSentEvents() { // sentEvents.clear(); // } // // private String transformToJson(Object value) { // try { // return objectMapper.writeValueAsString(value); // } catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // private static ObjectMapper createDefaultObjectMapper() { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.registerModules(new Jdk8Module(), new ParameterNamesModule(), new JavaTimeModule()); // objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // return objectMapper; // } // } // // Path: nakadi-producer/src/main/java/org/zalando/nakadiproducer/transmission/impl/EventTransmitter.java // public class EventTransmitter { // private final EventTransmissionService eventTransmissionService; // // public EventTransmitter(EventTransmissionService eventTransmissionService) { // this.eventTransmissionService = eventTransmissionService; // } // // public void sendEvents() { // eventTransmissionService.sendEvents(eventTransmissionService.lockSomeEvents()); // } // } // Path: nakadi-producer-starter-spring-boot-2-test/src/test/java/org/zalando/nakadiproducer/tests/ApplicationIT.java import org.junit.*; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient; import org.zalando.nakadiproducer.transmission.impl.EventTransmitter; import java.io.File; import java.util.List; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; package org.zalando.nakadiproducer.tests; @RunWith(SpringRunner.class) @SpringBootTest( // This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up // by our starter *even if* it has been defined *after* the application itself. This has been a problem until // this commit. classes = { Application.class, MockNakadiConfig.class }, properties = { "nakadi-producer.transmission-polling-delay=30"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) public class ApplicationIT { @LocalManagementPort private int localManagementPort; @ClassRule public static final EnvironmentVariables environmentVariables = new EnvironmentVariables(); @BeforeClass public static void fakeCredentialsDir() { environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath()); } @Autowired private MockNakadiPublishingClient mockClient; @Autowired
private EventTransmitter eventTransmitter;
batir-akhmerov/hybricache
hybricache/src/test/java/org/hybricache/needRedisRunning/ehCacheTests/EhCacheDaoAppTest.java
// Path: hybricache/src/test/java/org/hybricache/testDao/TestDao.java // public interface TestDao { // // TestBean findById(int id); // // TestBean findByName(String name); // // }
import org.hybricache.testDao.TestDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/** * */ package org.hybricache.needRedisRunning.ehCacheTests; /** * The EhCacheDaoAppTest class * * @author Batir Akhmerov * Created on Jan 26, 2017 */ public class EhCacheDaoAppTest { private static final Logger log = LoggerFactory.getLogger(EhCacheDaoAppTest.class); //@Test public void test() { ApplicationContext context = new AnnotationConfigApplicationContext(TestAppConfig.class);
// Path: hybricache/src/test/java/org/hybricache/testDao/TestDao.java // public interface TestDao { // // TestBean findById(int id); // // TestBean findByName(String name); // // } // Path: hybricache/src/test/java/org/hybricache/needRedisRunning/ehCacheTests/EhCacheDaoAppTest.java import org.hybricache.testDao.TestDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * */ package org.hybricache.needRedisRunning.ehCacheTests; /** * The EhCacheDaoAppTest class * * @author Batir Akhmerov * Created on Jan 26, 2017 */ public class EhCacheDaoAppTest { private static final Logger log = LoggerFactory.getLogger(EhCacheDaoAppTest.class); //@Test public void test() { ApplicationContext context = new AnnotationConfigApplicationContext(TestAppConfig.class);
TestDao obj = (TestDao) context.getBean("testDao");
batir-akhmerov/hybricache
hybricache/src/main/java/org/hybricache/BaseCache.java
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // }
import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache;
/** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes")
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // } // Path: hybricache/src/main/java/org/hybricache/BaseCache.java import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache; /** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes")
protected RemoteCache remoteCache;
batir-akhmerov/hybricache
hybricache/src/main/java/org/hybricache/BaseCache.java
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // }
import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache;
/** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes") protected RemoteCache remoteCache;
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // } // Path: hybricache/src/main/java/org/hybricache/BaseCache.java import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache; /** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes") protected RemoteCache remoteCache;
private HybriKeyCache hybriKeyCache;
batir-akhmerov/hybricache
hybricache/src/main/java/org/hybricache/BaseCache.java
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // }
import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache;
/** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes") protected RemoteCache remoteCache; private HybriKeyCache hybriKeyCache;
// Path: hybricache/src/main/java/org/hybricache/HybriCacheConfiguration.java // public enum CacheType{HYBRID, LOCAL, REMOTE}; // // Path: hybricache/src/main/java/org/hybricache/key/HybriKeyCache.java // public class HybriKeyCache extends BaseCache implements Cache { // // protected int keyTrustPeriod; // // // public HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) { // super(ehCacheNative, hybriCacheConfig, remoteCacheFactory); // this.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod(); // } // // public void removeBothHybriKeys(Object key){ // getEhCache().evict(key); // getRemoteCache().evict(key); // } // // public HybriKey getKeyRemote(Object key) { // HybriKey hybriKey = getRemoteCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyRemote(Object key, HybriKey hybriKey) { // getRemoteCache().put(key, hybriKey); // } // // public HybriKey getKeyLocal(Object key) { // HybriKey hybriKey = getEhCache().get(key, HybriKey.class); // if (hybriKey == null) { // hybriKey = new HybriKey(); // } // return hybriKey; // } // public void putKeyLocal(Object key, HybriKey hybriKey) { // getEhCache().put(key, hybriKey); // } // // // public boolean isKeyRecent(HybriKey keyLocal) { // long currentTime = System.currentTimeMillis(); // boolean isRecent = keyLocal != null && !keyLocal.isUndefined() // && (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod; // // System.out.println("TIME DIFF: " + (currentTime - keyLocal.getLastAccessedTime())); // return isRecent; // } // public boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) { // return keyLocal != null && keyRemote != null // && !keyLocal.isUndefined() && !keyRemote.isUndefined() // && keyLocal.getRevision() == keyRemote.getRevision(); // } // // // // // // // // @Override // public String getName() { // // TODO Auto-generated method stub // return null; // } // // @Override // public Object getNativeCache() { // // TODO Auto-generated method stub // return null; // } // // @Override // public ValueWrapper get(Object key) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Class<T> type) { // // TODO Auto-generated method stub // return null; // } // // @Override // public <T> T get(Object key, Callable<T> valueLoader) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void put(Object key, Object value) { // // TODO Auto-generated method stub // // } // // @Override // public ValueWrapper putIfAbsent(Object key, Object value) { // // TODO Auto-generated method stub // return null; // } // // @Override // public void evict(Object key) { // // TODO Auto-generated method stub // // } // // @Override // public void clear() { // // TODO Auto-generated method stub // // } // // public int getKeyTrustPeriod() { // return this.keyTrustPeriod; // } // // public void setKeyTrustPeriod(int keyTrustPeriod) { // this.keyTrustPeriod = keyTrustPeriod; // } // // // // // // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCache.java // public interface RemoteCache<C> extends Cache { // // public C getCacheTarget(); // // } // // Path: hybricache/src/main/java/org/hybricache/remote/RemoteCacheFactory.java // public interface RemoteCacheFactory { // // @SuppressWarnings("rawtypes") // public RemoteCache getInstance(HybriCacheConfiguration conf); // // } // Path: hybricache/src/main/java/org/hybricache/BaseCache.java import org.hybricache.HybriCacheConfiguration.CacheType; import org.hybricache.key.HybriKeyCache; import org.hybricache.remote.RemoteCache; import org.hybricache.remote.RemoteCacheFactory; import org.springframework.cache.ehcache.EhCacheCache; import net.sf.ehcache.Ehcache; /** * */ package org.hybricache; /** * The BaseCache class * * @author Batir Akhmerov * Created on Feb 4, 2017 */ public class BaseCache { protected EhCacheCache ehCache; protected HybriCacheConfiguration hybriCacheConfig; @SuppressWarnings("rawtypes") protected RemoteCache remoteCache; private HybriKeyCache hybriKeyCache;
public BaseCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) {
batir-akhmerov/hybricache
hybricache/src/test/java/org/hybricache/needRedisRunning/configTests/HybriCacheAppConfig1.java
// Path: hybricache/src/test/java/org/hybricache/needRedisRunning/ehCacheTests/TestAppConfig.java // @Configuration // @ComponentScan({ "org.r3p.cache.*" }) // @PropertySource("classpath:application.properties") // public class TestAppConfig { // // @Inject protected Environment env; // // // @Bean // public HybriCacheManager cacheManager() { // String host = this.env.getProperty("remote.cache.server.host"); // String port = this.env.getProperty("remote.cache.server.port"); // Integer intPort = null; // if (port != null) { // intPort = Integer.parseInt(port); // } // HybriCacheManager cacheManager = new HybriCacheManager( new EhCacheCacheManager(ehCacheCacheManager().getObject()), host, intPort); // cacheManager.setHybriCacheConfigurationList(hybriCacheConfigurationList()); // cacheManager.setDefaultHybriCacheConfiguration(defaultHybriCacheConfiguration()); // return cacheManager; // } // // @Bean // public EhCacheManagerFactoryBean ehCacheCacheManager() { // EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean(); // cmfb.setConfigLocation(new ClassPathResource("ehcache.xml")); // cmfb.setShared(true); // return cmfb; // } // // @Bean // public HybriCacheConfiguration defaultHybriCacheConfiguration() { // int maxEntriesLocalHeap = 0; // // return new HybriCacheConfiguration( // CacheType.HYBRID, // 1000, // new CacheConfiguration("defaultCache", maxEntriesLocalHeap) // .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) // .eternal(false) // .timeToLiveSeconds(60) // .timeToIdleSeconds(30) // .diskExpiryThreadIntervalSeconds(0) // .persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)) // ); // // } // // // @Bean // public List<HybriCacheConfiguration> hybriCacheConfigurationList() { // return null; // } // // }
import org.hybricache.needRedisRunning.ehCacheTests.TestAppConfig; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource;
/** * */ package org.hybricache.needRedisRunning.configTests; /** * The HybriCacheAppConfig1 class * * @author Batir Akhmerov * Created on Jan 26, 2017 */ @Configuration @ComponentScan({ "org.r3p.cache.*" }) @PropertySource("classpath:application.properties")
// Path: hybricache/src/test/java/org/hybricache/needRedisRunning/ehCacheTests/TestAppConfig.java // @Configuration // @ComponentScan({ "org.r3p.cache.*" }) // @PropertySource("classpath:application.properties") // public class TestAppConfig { // // @Inject protected Environment env; // // // @Bean // public HybriCacheManager cacheManager() { // String host = this.env.getProperty("remote.cache.server.host"); // String port = this.env.getProperty("remote.cache.server.port"); // Integer intPort = null; // if (port != null) { // intPort = Integer.parseInt(port); // } // HybriCacheManager cacheManager = new HybriCacheManager( new EhCacheCacheManager(ehCacheCacheManager().getObject()), host, intPort); // cacheManager.setHybriCacheConfigurationList(hybriCacheConfigurationList()); // cacheManager.setDefaultHybriCacheConfiguration(defaultHybriCacheConfiguration()); // return cacheManager; // } // // @Bean // public EhCacheManagerFactoryBean ehCacheCacheManager() { // EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean(); // cmfb.setConfigLocation(new ClassPathResource("ehcache.xml")); // cmfb.setShared(true); // return cmfb; // } // // @Bean // public HybriCacheConfiguration defaultHybriCacheConfiguration() { // int maxEntriesLocalHeap = 0; // // return new HybriCacheConfiguration( // CacheType.HYBRID, // 1000, // new CacheConfiguration("defaultCache", maxEntriesLocalHeap) // .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) // .eternal(false) // .timeToLiveSeconds(60) // .timeToIdleSeconds(30) // .diskExpiryThreadIntervalSeconds(0) // .persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)) // ); // // } // // // @Bean // public List<HybriCacheConfiguration> hybriCacheConfigurationList() { // return null; // } // // } // Path: hybricache/src/test/java/org/hybricache/needRedisRunning/configTests/HybriCacheAppConfig1.java import org.hybricache.needRedisRunning.ehCacheTests.TestAppConfig; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; /** * */ package org.hybricache.needRedisRunning.configTests; /** * The HybriCacheAppConfig1 class * * @author Batir Akhmerov * Created on Jan 26, 2017 */ @Configuration @ComponentScan({ "org.r3p.cache.*" }) @PropertySource("classpath:application.properties")
public class HybriCacheAppConfig1 extends TestAppConfig {