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
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/services/ForegroundServiceConfig.java
// Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // }
import android.annotation.TargetApi; import android.app.Notification; import android.content.Context; import com.liulishuo.filedownloader.R; import com.liulishuo.filedownloader.util.FileDownloadLog;
/* * Copyright (c) 2015 LingoChamp 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.liulishuo.filedownloader.services; @TargetApi(26) public class ForegroundServiceConfig { private int notificationId; private String notificationChannelId; private String notificationChannelName; private Notification notification; private boolean needRecreateChannelId; private ForegroundServiceConfig() { } private static final String DEFAULT_NOTIFICATION_CHANNEL_ID = "filedownloader_channel"; private static final String DEFAULT_NOTIFICATION_CHANNEL_NAME = "Filedownloader"; private static final int DEFAULT_NOTIFICATION_ID = android.R.drawable.arrow_down_float; public int getNotificationId() { return notificationId; } public String getNotificationChannelId() { return notificationChannelId; } public String getNotificationChannelName() { return notificationChannelName; } public Notification getNotification(Context context) { if (notification == null) {
// Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // } // Path: library/src/main/java/com/liulishuo/filedownloader/services/ForegroundServiceConfig.java import android.annotation.TargetApi; import android.app.Notification; import android.content.Context; import com.liulishuo.filedownloader.R; import com.liulishuo.filedownloader.util.FileDownloadLog; /* * Copyright (c) 2015 LingoChamp 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.liulishuo.filedownloader.services; @TargetApi(26) public class ForegroundServiceConfig { private int notificationId; private String notificationChannelId; private String notificationChannelName; private Notification notification; private boolean needRecreateChannelId; private ForegroundServiceConfig() { } private static final String DEFAULT_NOTIFICATION_CHANNEL_ID = "filedownloader_channel"; private static final String DEFAULT_NOTIFICATION_CHANNEL_NAME = "Filedownloader"; private static final int DEFAULT_NOTIFICATION_ID = android.R.drawable.arrow_down_float; public int getNotificationId() { return notificationId; } public String getNotificationChannelId() { return notificationChannelId; } public String getNotificationChannelName() { return notificationChannelName; } public Notification getNotification(Context context) { if (notification == null) {
if (FileDownloadLog.NEED_LOG) {
lingochamp/FileDownloader
library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java
// Path: library/src/main/java/com/liulishuo/filedownloader/connection/FileDownloadConnection.java // @SuppressWarnings("EmptyMethod") // public interface FileDownloadConnection { // int NO_RESPONSE_CODE = 0; // int RESPONSE_CODE_FROM_OFFSET = 1; // // /** // * Sets the header named {@code name} to {@code value}. // * <p> // * The capacity of this method is similar to the // * {@link URLConnection#addRequestProperty(String, String)} // */ // void addHeader(String name, String value); // // /** // * If we find the file has been downloaded several bytes, we will try to resume from the // * breakpoint from {@code offset} length. // * // * @param etag the etag is stored by the past downloaded. // * @param offset the offset length has already been downloaded. // * @return {@code true} if adding resume offset was dispatched, so we can't handle that by // * internal. // */ // @SuppressWarnings("UnusedParameters") // boolean dispatchAddResumeOffset(String etag, long offset); // // /** // * Returns an input stream that reads from this open connection. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getInputStream()} // * // * @return an input stream that reads from this open connection. // */ // InputStream getInputStream() throws IOException; // // /** // * Returns an unmodifiable Map of general request header fields for this connection. The Map // * keys are Strings that represent the request-header field names. Each Map value is a // * unmodifiable List of Strings that represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getRequestProperties()} // * // * @return a Map of the general request properties for this connection. // */ // Map<String, List<String>> getRequestHeaderFields(); // // /** // * Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent // * the response-header field names. Each Map value is an unmodifiable List of Strings that // * represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getHeaderFields()} // * // * @return a Map of header fields // */ // Map<String, List<String>> getResponseHeaderFields(); // // /** // * Returns the value of the named header field, which would be the response-header field. // * <p> // * If called on a connection that sets the same header multiple times // * with possibly different values, only the last value is returned. // * // * @param name the name of a header field. // * @return the value of the named header field, or <code>null</code> // * if there is no such field in the header. // */ // String getResponseHeaderField(String name); // // /** // * Set the method for the request, one of: // * <UL> // * <LI>GET // * <LI>POST // * <LI>HEAD // * <LI>OPTIONS // * <LI>PUT // * <LI>DELETE // * <LI>TRACE // * </UL> are legal, subject to protocol restrictions. The default // * method is GET. // * // * @param method the HTTP method // * @exception ProtocolException if the method cannot be reset or if // * the requested method isn't valid for HTTP. // * @exception SecurityException if a security manager is set and the // * method is "TRACE", but the "allowHttpTrace" // * NetPermission is not granted. // * // * @return {@code true} if set effect, otherwise {@code false}. // */ // boolean setRequestMethod(String method) throws ProtocolException; // // /** // * Invokes the request immediately, and blocks until the response can be processed or is in // * error. // */ // void execute() throws IOException; // // /** // * Gets the status code from an HTTP response message. // * <p> // * <strong>If this is not http/https protocol connection</strong>: // * 1. If you make sure this connection is resume from the offset breakpoint(which you can check // * out this through {@link #dispatchAddResumeOffset(String, long)}), please return // * {@link #RESPONSE_CODE_FROM_OFFSET} // * 2. otherwise, return {@link #NO_RESPONSE_CODE}. // * // * @return the HTTP Status-Code, or -1 // */ // int getResponseCode() throws IOException; // // /** // * To Be Reused or Close this connection, since this connection is ending in this session. // */ // void ending(); // } // // Path: library/src/main/java/com/liulishuo/filedownloader/exception/FileDownloadSecurityException.java // public class FileDownloadSecurityException extends Exception { // public FileDownloadSecurityException(String msg) { // super(msg); // } // }
import com.liulishuo.filedownloader.connection.FileDownloadConnection; import com.liulishuo.filedownloader.exception.FileDownloadSecurityException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
@Test public void parseContentLengthFromContentRange_withNullContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(null); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withEmptyContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(""); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withStartToEndRange() { long length = FileDownloadUtils .parseContentLengthFromContentRange("bytes 25086300-37629450/37629451"); assertThat(length).isEqualTo(12543151); } @Test public void parseContentLengthFromContentRange_withUnavailableContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange("bytes 0-/37629451"); assertThat(length).isEqualTo(-1); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test
// Path: library/src/main/java/com/liulishuo/filedownloader/connection/FileDownloadConnection.java // @SuppressWarnings("EmptyMethod") // public interface FileDownloadConnection { // int NO_RESPONSE_CODE = 0; // int RESPONSE_CODE_FROM_OFFSET = 1; // // /** // * Sets the header named {@code name} to {@code value}. // * <p> // * The capacity of this method is similar to the // * {@link URLConnection#addRequestProperty(String, String)} // */ // void addHeader(String name, String value); // // /** // * If we find the file has been downloaded several bytes, we will try to resume from the // * breakpoint from {@code offset} length. // * // * @param etag the etag is stored by the past downloaded. // * @param offset the offset length has already been downloaded. // * @return {@code true} if adding resume offset was dispatched, so we can't handle that by // * internal. // */ // @SuppressWarnings("UnusedParameters") // boolean dispatchAddResumeOffset(String etag, long offset); // // /** // * Returns an input stream that reads from this open connection. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getInputStream()} // * // * @return an input stream that reads from this open connection. // */ // InputStream getInputStream() throws IOException; // // /** // * Returns an unmodifiable Map of general request header fields for this connection. The Map // * keys are Strings that represent the request-header field names. Each Map value is a // * unmodifiable List of Strings that represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getRequestProperties()} // * // * @return a Map of the general request properties for this connection. // */ // Map<String, List<String>> getRequestHeaderFields(); // // /** // * Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent // * the response-header field names. Each Map value is an unmodifiable List of Strings that // * represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getHeaderFields()} // * // * @return a Map of header fields // */ // Map<String, List<String>> getResponseHeaderFields(); // // /** // * Returns the value of the named header field, which would be the response-header field. // * <p> // * If called on a connection that sets the same header multiple times // * with possibly different values, only the last value is returned. // * // * @param name the name of a header field. // * @return the value of the named header field, or <code>null</code> // * if there is no such field in the header. // */ // String getResponseHeaderField(String name); // // /** // * Set the method for the request, one of: // * <UL> // * <LI>GET // * <LI>POST // * <LI>HEAD // * <LI>OPTIONS // * <LI>PUT // * <LI>DELETE // * <LI>TRACE // * </UL> are legal, subject to protocol restrictions. The default // * method is GET. // * // * @param method the HTTP method // * @exception ProtocolException if the method cannot be reset or if // * the requested method isn't valid for HTTP. // * @exception SecurityException if a security manager is set and the // * method is "TRACE", but the "allowHttpTrace" // * NetPermission is not granted. // * // * @return {@code true} if set effect, otherwise {@code false}. // */ // boolean setRequestMethod(String method) throws ProtocolException; // // /** // * Invokes the request immediately, and blocks until the response can be processed or is in // * error. // */ // void execute() throws IOException; // // /** // * Gets the status code from an HTTP response message. // * <p> // * <strong>If this is not http/https protocol connection</strong>: // * 1. If you make sure this connection is resume from the offset breakpoint(which you can check // * out this through {@link #dispatchAddResumeOffset(String, long)}), please return // * {@link #RESPONSE_CODE_FROM_OFFSET} // * 2. otherwise, return {@link #NO_RESPONSE_CODE}. // * // * @return the HTTP Status-Code, or -1 // */ // int getResponseCode() throws IOException; // // /** // * To Be Reused or Close this connection, since this connection is ending in this session. // */ // void ending(); // } // // Path: library/src/main/java/com/liulishuo/filedownloader/exception/FileDownloadSecurityException.java // public class FileDownloadSecurityException extends Exception { // public FileDownloadSecurityException(String msg) { // super(msg); // } // } // Path: library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java import com.liulishuo.filedownloader.connection.FileDownloadConnection; import com.liulishuo.filedownloader.exception.FileDownloadSecurityException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test public void parseContentLengthFromContentRange_withNullContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(null); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withEmptyContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(""); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withStartToEndRange() { long length = FileDownloadUtils .parseContentLengthFromContentRange("bytes 25086300-37629450/37629451"); assertThat(length).isEqualTo(12543151); } @Test public void parseContentLengthFromContentRange_withUnavailableContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange("bytes 0-/37629451"); assertThat(length).isEqualTo(-1); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test
public void findFilename_securityIssue() throws FileDownloadSecurityException {
lingochamp/FileDownloader
library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java
// Path: library/src/main/java/com/liulishuo/filedownloader/connection/FileDownloadConnection.java // @SuppressWarnings("EmptyMethod") // public interface FileDownloadConnection { // int NO_RESPONSE_CODE = 0; // int RESPONSE_CODE_FROM_OFFSET = 1; // // /** // * Sets the header named {@code name} to {@code value}. // * <p> // * The capacity of this method is similar to the // * {@link URLConnection#addRequestProperty(String, String)} // */ // void addHeader(String name, String value); // // /** // * If we find the file has been downloaded several bytes, we will try to resume from the // * breakpoint from {@code offset} length. // * // * @param etag the etag is stored by the past downloaded. // * @param offset the offset length has already been downloaded. // * @return {@code true} if adding resume offset was dispatched, so we can't handle that by // * internal. // */ // @SuppressWarnings("UnusedParameters") // boolean dispatchAddResumeOffset(String etag, long offset); // // /** // * Returns an input stream that reads from this open connection. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getInputStream()} // * // * @return an input stream that reads from this open connection. // */ // InputStream getInputStream() throws IOException; // // /** // * Returns an unmodifiable Map of general request header fields for this connection. The Map // * keys are Strings that represent the request-header field names. Each Map value is a // * unmodifiable List of Strings that represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getRequestProperties()} // * // * @return a Map of the general request properties for this connection. // */ // Map<String, List<String>> getRequestHeaderFields(); // // /** // * Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent // * the response-header field names. Each Map value is an unmodifiable List of Strings that // * represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getHeaderFields()} // * // * @return a Map of header fields // */ // Map<String, List<String>> getResponseHeaderFields(); // // /** // * Returns the value of the named header field, which would be the response-header field. // * <p> // * If called on a connection that sets the same header multiple times // * with possibly different values, only the last value is returned. // * // * @param name the name of a header field. // * @return the value of the named header field, or <code>null</code> // * if there is no such field in the header. // */ // String getResponseHeaderField(String name); // // /** // * Set the method for the request, one of: // * <UL> // * <LI>GET // * <LI>POST // * <LI>HEAD // * <LI>OPTIONS // * <LI>PUT // * <LI>DELETE // * <LI>TRACE // * </UL> are legal, subject to protocol restrictions. The default // * method is GET. // * // * @param method the HTTP method // * @exception ProtocolException if the method cannot be reset or if // * the requested method isn't valid for HTTP. // * @exception SecurityException if a security manager is set and the // * method is "TRACE", but the "allowHttpTrace" // * NetPermission is not granted. // * // * @return {@code true} if set effect, otherwise {@code false}. // */ // boolean setRequestMethod(String method) throws ProtocolException; // // /** // * Invokes the request immediately, and blocks until the response can be processed or is in // * error. // */ // void execute() throws IOException; // // /** // * Gets the status code from an HTTP response message. // * <p> // * <strong>If this is not http/https protocol connection</strong>: // * 1. If you make sure this connection is resume from the offset breakpoint(which you can check // * out this through {@link #dispatchAddResumeOffset(String, long)}), please return // * {@link #RESPONSE_CODE_FROM_OFFSET} // * 2. otherwise, return {@link #NO_RESPONSE_CODE}. // * // * @return the HTTP Status-Code, or -1 // */ // int getResponseCode() throws IOException; // // /** // * To Be Reused or Close this connection, since this connection is ending in this session. // */ // void ending(); // } // // Path: library/src/main/java/com/liulishuo/filedownloader/exception/FileDownloadSecurityException.java // public class FileDownloadSecurityException extends Exception { // public FileDownloadSecurityException(String msg) { // super(msg); // } // }
import com.liulishuo.filedownloader.connection.FileDownloadConnection; import com.liulishuo.filedownloader.exception.FileDownloadSecurityException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
@Test public void parseContentLengthFromContentRange_withNullContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(null); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withEmptyContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(""); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withStartToEndRange() { long length = FileDownloadUtils .parseContentLengthFromContentRange("bytes 25086300-37629450/37629451"); assertThat(length).isEqualTo(12543151); } @Test public void parseContentLengthFromContentRange_withUnavailableContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange("bytes 0-/37629451"); assertThat(length).isEqualTo(-1); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void findFilename_securityIssue() throws FileDownloadSecurityException {
// Path: library/src/main/java/com/liulishuo/filedownloader/connection/FileDownloadConnection.java // @SuppressWarnings("EmptyMethod") // public interface FileDownloadConnection { // int NO_RESPONSE_CODE = 0; // int RESPONSE_CODE_FROM_OFFSET = 1; // // /** // * Sets the header named {@code name} to {@code value}. // * <p> // * The capacity of this method is similar to the // * {@link URLConnection#addRequestProperty(String, String)} // */ // void addHeader(String name, String value); // // /** // * If we find the file has been downloaded several bytes, we will try to resume from the // * breakpoint from {@code offset} length. // * // * @param etag the etag is stored by the past downloaded. // * @param offset the offset length has already been downloaded. // * @return {@code true} if adding resume offset was dispatched, so we can't handle that by // * internal. // */ // @SuppressWarnings("UnusedParameters") // boolean dispatchAddResumeOffset(String etag, long offset); // // /** // * Returns an input stream that reads from this open connection. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getInputStream()} // * // * @return an input stream that reads from this open connection. // */ // InputStream getInputStream() throws IOException; // // /** // * Returns an unmodifiable Map of general request header fields for this connection. The Map // * keys are Strings that represent the request-header field names. Each Map value is a // * unmodifiable List of Strings that represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getRequestProperties()} // * // * @return a Map of the general request properties for this connection. // */ // Map<String, List<String>> getRequestHeaderFields(); // // /** // * Returns an unmodifiable Map of the header fields. The Map keys are Strings that represent // * the response-header field names. Each Map value is an unmodifiable List of Strings that // * represents the corresponding field values. // * <p> // * The capacity of this method is similar to the {@link URLConnection#getHeaderFields()} // * // * @return a Map of header fields // */ // Map<String, List<String>> getResponseHeaderFields(); // // /** // * Returns the value of the named header field, which would be the response-header field. // * <p> // * If called on a connection that sets the same header multiple times // * with possibly different values, only the last value is returned. // * // * @param name the name of a header field. // * @return the value of the named header field, or <code>null</code> // * if there is no such field in the header. // */ // String getResponseHeaderField(String name); // // /** // * Set the method for the request, one of: // * <UL> // * <LI>GET // * <LI>POST // * <LI>HEAD // * <LI>OPTIONS // * <LI>PUT // * <LI>DELETE // * <LI>TRACE // * </UL> are legal, subject to protocol restrictions. The default // * method is GET. // * // * @param method the HTTP method // * @exception ProtocolException if the method cannot be reset or if // * the requested method isn't valid for HTTP. // * @exception SecurityException if a security manager is set and the // * method is "TRACE", but the "allowHttpTrace" // * NetPermission is not granted. // * // * @return {@code true} if set effect, otherwise {@code false}. // */ // boolean setRequestMethod(String method) throws ProtocolException; // // /** // * Invokes the request immediately, and blocks until the response can be processed or is in // * error. // */ // void execute() throws IOException; // // /** // * Gets the status code from an HTTP response message. // * <p> // * <strong>If this is not http/https protocol connection</strong>: // * 1. If you make sure this connection is resume from the offset breakpoint(which you can check // * out this through {@link #dispatchAddResumeOffset(String, long)}), please return // * {@link #RESPONSE_CODE_FROM_OFFSET} // * 2. otherwise, return {@link #NO_RESPONSE_CODE}. // * // * @return the HTTP Status-Code, or -1 // */ // int getResponseCode() throws IOException; // // /** // * To Be Reused or Close this connection, since this connection is ending in this session. // */ // void ending(); // } // // Path: library/src/main/java/com/liulishuo/filedownloader/exception/FileDownloadSecurityException.java // public class FileDownloadSecurityException extends Exception { // public FileDownloadSecurityException(String msg) { // super(msg); // } // } // Path: library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java import com.liulishuo.filedownloader.connection.FileDownloadConnection; import com.liulishuo.filedownloader.exception.FileDownloadSecurityException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test public void parseContentLengthFromContentRange_withNullContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(null); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withEmptyContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange(""); assertThat(length).isEqualTo(-1); } @Test public void parseContentLengthFromContentRange_withStartToEndRange() { long length = FileDownloadUtils .parseContentLengthFromContentRange("bytes 25086300-37629450/37629451"); assertThat(length).isEqualTo(12543151); } @Test public void parseContentLengthFromContentRange_withUnavailableContentRange() { long length = FileDownloadUtils.parseContentLengthFromContentRange("bytes 0-/37629451"); assertThat(length).isEqualTo(-1); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void findFilename_securityIssue() throws FileDownloadSecurityException {
final FileDownloadConnection connection = mock(FileDownloadConnection.class);
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // }
import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor;
/* * Copyright (c) 2015 LingoChamp 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.liulishuo.filedownloader; /** * The global launcher for launching tasks. */ class FileDownloadTaskLauncher { private static class HolderClass { private static final FileDownloadTaskLauncher INSTANCE = new FileDownloadTaskLauncher(); static { // We add the message receiver to the message snapshot flow central, when there is a // task request to launch.
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // } // Path: library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; /* * Copyright (c) 2015 LingoChamp 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.liulishuo.filedownloader; /** * The global launcher for launching tasks. */ class FileDownloadTaskLauncher { private static class HolderClass { private static final FileDownloadTaskLauncher INSTANCE = new FileDownloadTaskLauncher(); static { // We add the message receiver to the message snapshot flow central, when there is a // task request to launch.
MessageSnapshotFlow.getImpl().setReceiver(new MessageSnapshotGate());
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // }
import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor;
private static class LaunchTaskPool { private ThreadPoolExecutor mPool; /** * the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. */ private LinkedBlockingQueue<Runnable> mWorkQueue; LaunchTaskPool() { init(); } public void asyncExecute(final ITaskHunter.IStarter taskStarter) { mPool.execute(new LaunchTaskRunnable(taskStarter)); } public void expire(ITaskHunter.IStarter starter) { /** * @see LaunchTaskRunnable#equals(Object) */ //noinspection SuspiciousMethodCalls mWorkQueue.remove(starter); } public void expire(final FileDownloadListener listener) { if (listener == null) {
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // } // Path: library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; private static class LaunchTaskPool { private ThreadPoolExecutor mPool; /** * the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. */ private LinkedBlockingQueue<Runnable> mWorkQueue; LaunchTaskPool() { init(); } public void asyncExecute(final ITaskHunter.IStarter taskStarter) { mPool.execute(new LaunchTaskRunnable(taskStarter)); } public void expire(ITaskHunter.IStarter starter) { /** * @see LaunchTaskRunnable#equals(Object) */ //noinspection SuspiciousMethodCalls mWorkQueue.remove(starter); } public void expire(final FileDownloadListener listener) { if (listener == null) {
FileDownloadLog.w(this, "want to expire by listener, but the listener provided is"
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // }
import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor;
needPauseList.add(runnable); } } if (needPauseList.isEmpty()) { return; } if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "expire %d tasks with listener[%s]", needPauseList.size(), listener); } for (Runnable runnable : needPauseList) { mPool.remove(runnable); } } public void expireAll() { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "expire %d tasks", mWorkQueue.size()); } mPool.shutdownNow(); init(); } private void init() { mWorkQueue = new LinkedBlockingQueue<>();
// Path: library/src/main/java/com/liulishuo/filedownloader/message/MessageSnapshotFlow.java // public class MessageSnapshotFlow { // // private volatile MessageSnapshotThreadPool flowThreadPool; // private volatile MessageReceiver receiver; // // public static final class HolderClass { // private static final MessageSnapshotFlow INSTANCE = new MessageSnapshotFlow(); // } // // public static MessageSnapshotFlow getImpl() { // return HolderClass.INSTANCE; // } // // public void setReceiver(MessageReceiver receiver) { // this.receiver = receiver; // if (receiver == null) { // this.flowThreadPool = null; // } else { // this.flowThreadPool = new MessageSnapshotThreadPool(5, receiver); // } // } // // public void inflow(final MessageSnapshot snapshot) { // if (snapshot instanceof IFlowDirectly) { // if (receiver != null) { // receiver.receive(snapshot); // } // } else { // if (flowThreadPool != null) { // flowThreadPool.execute(snapshot); // } // } // // } // // // public interface MessageReceiver { // void receive(MessageSnapshot snapshot); // } // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadExecutors.java // public class FileDownloadExecutors { // private static final int DEFAULT_IDLE_SECOND = 15; // // public static ThreadPoolExecutor newFixedThreadPool(String prefix) { // return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, // new SynchronousQueue<Runnable>(), new FileDownloadThreadFactory(prefix)); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, String prefix) { // return newDefaultThreadPool(nThreads, new LinkedBlockingQueue<Runnable>(), prefix); // } // // public static ThreadPoolExecutor newDefaultThreadPool(int nThreads, // LinkedBlockingQueue<Runnable> queue, // String prefix) { // final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, // DEFAULT_IDLE_SECOND, TimeUnit.SECONDS, queue, // new FileDownloadThreadFactory(prefix)); // executor.allowCoreThreadTimeOut(true); // return executor; // } // // static class FileDownloadThreadFactory implements ThreadFactory { // private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); // private final String namePrefix; // private final ThreadGroup group; // private final AtomicInteger threadNumber = new AtomicInteger(1); // // FileDownloadThreadFactory(String prefix) { // group = Thread.currentThread().getThreadGroup(); // namePrefix = FileDownloadUtils.getThreadPoolName(prefix); // } // // @Override // public Thread newThread(Runnable r) { // Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // // if (t.isDaemon()) t.setDaemon(false); // if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); // return t; // } // } // // } // // Path: library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadLog.java // public class FileDownloadLog { // // public static boolean NEED_LOG = false; // // private static final String TAG = "FileDownloader."; // // public static void e(Object o, Throwable e, String msg, Object... args) { // log(Log.ERROR, o, e, msg, args); // } // // public static void e(Object o, String msg, Object... args) { // log(Log.ERROR, o, msg, args); // } // // public static void i(Object o, String msg, Object... args) { // log(Log.INFO, o, msg, args); // } // // public static void d(Object o, String msg, Object... args) { // log(Log.DEBUG, o, msg, args); // } // // public static void w(Object o, String msg, Object... args) { // log(Log.WARN, o, msg, args); // } // // public static void v(Object o, String msg, Object... args) { // log(Log.VERBOSE, o, msg, args); // } // // private static void log(int priority, Object o, String message, Object... args) { // log(priority, o, null, message, args); // } // // private static void log(int priority, Object o, Throwable throwable, String message, // Object... args) { // final boolean force = priority >= Log.WARN; // if (!force && !NEED_LOG) { // return; // } // // Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args)); // if (throwable != null) { // throwable.printStackTrace(); // } // } // // private static String getTag(final Object o) { // return TAG + ((o instanceof Class) // ? ((Class) o).getSimpleName() : o.getClass().getSimpleName()); // } // } // Path: library/src/main/java/com/liulishuo/filedownloader/FileDownloadTaskLauncher.java import com.liulishuo.filedownloader.message.MessageSnapshotFlow; import com.liulishuo.filedownloader.util.FileDownloadExecutors; import com.liulishuo.filedownloader.util.FileDownloadLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; needPauseList.add(runnable); } } if (needPauseList.isEmpty()) { return; } if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "expire %d tasks with listener[%s]", needPauseList.size(), listener); } for (Runnable runnable : needPauseList) { mPool.remove(runnable); } } public void expireAll() { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "expire %d tasks", mWorkQueue.size()); } mPool.shutdownNow(); init(); } private void init() { mWorkQueue = new LinkedBlockingQueue<>();
mPool = FileDownloadExecutors.newDefaultThreadPool(3, mWorkQueue, "LauncherTask");
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/activity/DiAppCompatActivity.java
// Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DiActivityModule.java // @Module(injects = { // DiAppCompatActivity.class, PhotosListActivity.class, PhotoDetailsActivity.class // }, addsTo = AppModule.class) public class DiActivityModule { // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import butterknife.ButterKnife; import com.photoviewer.presentation.PhotoViewerApplication; import com.photoviewer.presentation.di.modules.DiActivityModule;
package com.photoviewer.presentation.view.activity; public class DiAppCompatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) {
// Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DiActivityModule.java // @Module(injects = { // DiAppCompatActivity.class, PhotosListActivity.class, PhotoDetailsActivity.class // }, addsTo = AppModule.class) public class DiActivityModule { // } // Path: app/src/main/java/com/photoviewer/presentation/view/activity/DiAppCompatActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import butterknife.ButterKnife; import com.photoviewer.presentation.PhotoViewerApplication; import com.photoviewer.presentation.di.modules.DiActivityModule; package com.photoviewer.presentation.view.activity; public class DiAppCompatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) {
PhotoViewerApplication.getScopedGraph(new DiActivityModule()).inject(this);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/activity/DiAppCompatActivity.java
// Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DiActivityModule.java // @Module(injects = { // DiAppCompatActivity.class, PhotosListActivity.class, PhotoDetailsActivity.class // }, addsTo = AppModule.class) public class DiActivityModule { // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import butterknife.ButterKnife; import com.photoviewer.presentation.PhotoViewerApplication; import com.photoviewer.presentation.di.modules.DiActivityModule;
package com.photoviewer.presentation.view.activity; public class DiAppCompatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) {
// Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DiActivityModule.java // @Module(injects = { // DiAppCompatActivity.class, PhotosListActivity.class, PhotoDetailsActivity.class // }, addsTo = AppModule.class) public class DiActivityModule { // } // Path: app/src/main/java/com/photoviewer/presentation/view/activity/DiAppCompatActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import butterknife.ButterKnife; import com.photoviewer.presentation.PhotoViewerApplication; import com.photoviewer.presentation.di.modules.DiActivityModule; package com.photoviewer.presentation.view.activity; public class DiAppCompatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) {
PhotoViewerApplication.getScopedGraph(new DiActivityModule()).inject(this);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/db/DatabaseHelper.java
// Path: app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java // public class CreatePhotosTable extends Migration { // @Override // public void up(SQLiteDatabase db, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, PhotoEntity.class); // } catch (SQLException e) { // Log.wtf(DatabaseManager.LOG_TAG_DB, "Creation of PhotosTable failed", e); // } // } // } // // Path: app/src/main/java/com/photoviewer/data/db/migrations/Migration.java // public abstract class Migration { // public abstract void up(SQLiteDatabase db, ConnectionSource connectionSource); // // void addColumns(SQLiteDatabase db, String tableName, String... columnDefinitions) { // for (String definition : columnDefinitions) { // String sql = generateAddColumnSql(tableName, definition); // String columnName = definition.split(" ")[0]; // if (!columnExists(db, tableName, columnName)) { // db.execSQL(sql); // } // } // } // // boolean columnExists(SQLiteDatabase db, String tableName, String columnName) { // String sql = "PRAGMA TABLE_INFO(" + tableName + ")"; // Cursor cursor = db.rawQuery(sql, null); // // cursor.moveToFirst(); // // do { // String candidateColumnName = cursor.getString(cursor.getColumnIndex("name")); // // if (candidateColumnName.equals(columnName)) { // cursor.close(); // return true; // } // } while (cursor.moveToNext()); // // cursor.close(); // // return false; // } // // private String generateAddColumnSql(String tableName, String columnDefinition) { // return "ALTER TABLE " + tableName + " ADD COLUMN " + columnDefinition; // } // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.photoviewer.data.db.migrations.CreatePhotosTable; import com.photoviewer.data.db.migrations.Migration;
package com.photoviewer.data.db; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final Migration[] MIGRATIONS = new Migration[]{
// Path: app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java // public class CreatePhotosTable extends Migration { // @Override // public void up(SQLiteDatabase db, ConnectionSource connectionSource) { // try { // TableUtils.createTable(connectionSource, PhotoEntity.class); // } catch (SQLException e) { // Log.wtf(DatabaseManager.LOG_TAG_DB, "Creation of PhotosTable failed", e); // } // } // } // // Path: app/src/main/java/com/photoviewer/data/db/migrations/Migration.java // public abstract class Migration { // public abstract void up(SQLiteDatabase db, ConnectionSource connectionSource); // // void addColumns(SQLiteDatabase db, String tableName, String... columnDefinitions) { // for (String definition : columnDefinitions) { // String sql = generateAddColumnSql(tableName, definition); // String columnName = definition.split(" ")[0]; // if (!columnExists(db, tableName, columnName)) { // db.execSQL(sql); // } // } // } // // boolean columnExists(SQLiteDatabase db, String tableName, String columnName) { // String sql = "PRAGMA TABLE_INFO(" + tableName + ")"; // Cursor cursor = db.rawQuery(sql, null); // // cursor.moveToFirst(); // // do { // String candidateColumnName = cursor.getString(cursor.getColumnIndex("name")); // // if (candidateColumnName.equals(columnName)) { // cursor.close(); // return true; // } // } while (cursor.moveToNext()); // // cursor.close(); // // return false; // } // // private String generateAddColumnSql(String tableName, String columnDefinition) { // return "ALTER TABLE " + tableName + " ADD COLUMN " + columnDefinition; // } // } // Path: app/src/main/java/com/photoviewer/data/db/DatabaseHelper.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.photoviewer.data.db.migrations.CreatePhotosTable; import com.photoviewer.data.db.migrations.Migration; package com.photoviewer.data.db; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final Migration[] MIGRATIONS = new Migration[]{
new CreatePhotosTable()
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // } // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton
public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // } // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton
public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) { return repository; }
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // } // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) { return repository; }
@Provides @Singleton public PhotoStatisticsRepository providesPhotoStatisticsRepository(
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) { return repository; } @Provides @Singleton public PhotoStatisticsRepository providesPhotoStatisticsRepository(
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoRepository.java // public interface PhotoRepository { // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // Observable<List<PhotoEntity>> photos(); // // /** // * Get an {@link rx.Observable} which will emit a List of {@link PhotoEntity}, // * whom titles match searched title. // * @param title The photos' Title used to retrieve photo data. // */ // Observable<List<PhotoEntity>> searchPhotosByTitle(String title); // // /** // * Get an {@link rx.Observable} which will emit a {@link PhotoEntity}. // * // * @param photoId The photo id used to retrieve photo data. // */ // Observable<PhotoEntity> photo(final int photoId); // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // } // Path: app/src/main/java/com/photoviewer/presentation/di/modules/DataModule.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.repository.PhotoRepository; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class DataModule { @Provides @Singleton public PhotoRepository providesPhotoRepository(PhotoEntityDataSource repository) { return repository; } @Provides @Singleton public PhotoStatisticsRepository providesPhotoStatisticsRepository(
PhotoStatisticsEntityDataSource repository) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/PhotoListView.java
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // }
import com.photoviewer.presentation.model.PhotoStatisticsModel; import java.util.Collection; import com.photoviewer.presentation.model.PhotoModel;
/** * Copyright (C) 2014 android10.org. All rights reserved. * * @author Fernando Cejas (the android10 coder) */ package com.photoviewer.presentation.view; /** * Interface representing a View in a model view presenter (MVP) pattern. * In this case is used as a view representing a list of {@link PhotoModel}. */ public interface PhotoListView extends LoadDataView { /** * Render a photo list in the UI. * * @param photoModelCollection The collection of {@link PhotoModel} that will be shown. */ void renderPhotoList(Collection<PhotoModel> photoModelCollection); /** * View a {@link PhotoModel} profile/details. * * @param photoModel The photo that will be shown. */ void viewPhoto(PhotoModel photoModel); /** * View a {@link PhotoStatisticsModel} profile/details. * * @param photoStatisticsModel The PhotoStatisticsModel that will be shown. */
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // } // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoListView.java import com.photoviewer.presentation.model.PhotoStatisticsModel; import java.util.Collection; import com.photoviewer.presentation.model.PhotoModel; /** * Copyright (C) 2014 android10.org. All rights reserved. * * @author Fernando Cejas (the android10 coder) */ package com.photoviewer.presentation.view; /** * Interface representing a View in a model view presenter (MVP) pattern. * In this case is used as a view representing a list of {@link PhotoModel}. */ public interface PhotoListView extends LoadDataView { /** * Render a photo list in the UI. * * @param photoModelCollection The collection of {@link PhotoModel} that will be shown. */ void renderPhotoList(Collection<PhotoModel> photoModelCollection); /** * View a {@link PhotoModel} profile/details. * * @param photoModel The photo that will be shown. */ void viewPhoto(PhotoModel photoModel); /** * View a {@link PhotoStatisticsModel} profile/details. * * @param photoStatisticsModel The PhotoStatisticsModel that will be shown. */
void renderPhotoStatisticsModel(PhotoStatisticsModel photoStatisticsModel);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoStatistics extends UseCase<PhotoStatistics> { @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource; @Inject GetPhotoDetails mGetPhotoDetailsUseCase;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoStatistics.java import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoStatistics extends UseCase<PhotoStatistics> { @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource; @Inject GetPhotoDetails mGetPhotoDetailsUseCase;
@Inject public GetPhotoStatistics(@Named(RxModule.COMPUTATION) Scheduler executionScheduler,
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/repository/datastore/DatabasePhotoEntityStore.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // }
import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.misc.TransactionManager; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; import java.util.Collection; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber;
package com.photoviewer.data.repository.datastore; public class DatabasePhotoEntityStore { private static final String LOG_TAG = DatabasePhotoEntityStore.class.getSimpleName(); private static final String PERCENT = "%";
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // } // Path: app/src/main/java/com/photoviewer/data/repository/datastore/DatabasePhotoEntityStore.java import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.misc.TransactionManager; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; import java.util.Collection; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; package com.photoviewer.data.repository.datastore; public class DatabasePhotoEntityStore { private static final String LOG_TAG = DatabasePhotoEntityStore.class.getSimpleName(); private static final String PERCENT = "%";
private Dao<PhotoEntity, Integer> mPhotosDao;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/repository/datastore/DatabasePhotoEntityStore.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // }
import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.misc.TransactionManager; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; import java.util.Collection; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber;
package com.photoviewer.data.repository.datastore; public class DatabasePhotoEntityStore { private static final String LOG_TAG = DatabasePhotoEntityStore.class.getSimpleName(); private static final String PERCENT = "%"; private Dao<PhotoEntity, Integer> mPhotosDao; //Search prepared fields, for faster search private PreparedQuery<PhotoEntity> mSearchByTitleQuery; private SelectArg mSearchByTitleQuerySelectArg; @Inject
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // } // Path: app/src/main/java/com/photoviewer/data/repository/datastore/DatabasePhotoEntityStore.java import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.misc.TransactionManager; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; import java.util.Collection; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; package com.photoviewer.data.repository.datastore; public class DatabasePhotoEntityStore { private static final String LOG_TAG = DatabasePhotoEntityStore.class.getSimpleName(); private static final String PERCENT = "%"; private Dao<PhotoEntity, Integer> mPhotosDao; //Search prepared fields, for faster search private PreparedQuery<PhotoEntity> mSearchByTitleQuery; private SelectArg mSearchByTitleQuerySelectArg; @Inject
public DatabasePhotoEntityStore(DatabaseManager databaseManager) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotosList.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; public class GetPhotosList extends UseCase<List<Photo>> { private PhotoEntityDataSource mPhotoEntityDataSource;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotosList.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; public class GetPhotosList extends UseCase<List<Photo>> { private PhotoEntityDataSource mPhotoEntityDataSource;
private final PhotoEntityToPhoto mPhotoTransformer;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotosList.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; public class GetPhotosList extends UseCase<List<Photo>> { private PhotoEntityDataSource mPhotoEntityDataSource; private final PhotoEntityToPhoto mPhotoTransformer;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotosList.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; public class GetPhotosList extends UseCase<List<Photo>> { private PhotoEntityDataSource mPhotoEntityDataSource; private final PhotoEntityToPhoto mPhotoTransformer;
@Inject public GetPhotosList(@Named(RxModule.COMPUTATION) Scheduler executionScheduler,
lifedemons/photoviewer
app/src/androidTest/java/com/photoviewer/common/steps/PageObject.java
// Path: app/src/androidTest/java/com/photoviewer/di/TestsModule.java // @Module(injects = { PageObject.class, PhotosListPage.class }, addsTo = AppModule.class) // public class TestsModule { // } // // Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // }
import android.app.Activity; import android.support.test.espresso.Espresso; import android.support.test.espresso.IdlingResource; import android.support.test.rule.ActivityTestRule; import com.jakewharton.espresso.OkHttp3IdlingResource; import com.photoviewer.di.TestsModule; import com.photoviewer.presentation.PhotoViewerApplication; import javax.inject.Inject; import okhttp3.OkHttpClient; import org.junit.Rule;
package com.photoviewer.common.steps; public class PageObject<T extends Activity> { @Rule public ActivityTestRule<T> mActivityRule; @Inject OkHttpClient mOkHttpClient; private T mActivity; private IdlingResource mOkHttp3IdlingResource; public PageObject(Class<T> activityClass) { mActivityRule = new ActivityTestRule<>(activityClass, false, false); injectFieldsFromApp(); setUpIdlingResources(); } private void injectFieldsFromApp() {
// Path: app/src/androidTest/java/com/photoviewer/di/TestsModule.java // @Module(injects = { PageObject.class, PhotosListPage.class }, addsTo = AppModule.class) // public class TestsModule { // } // // Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // Path: app/src/androidTest/java/com/photoviewer/common/steps/PageObject.java import android.app.Activity; import android.support.test.espresso.Espresso; import android.support.test.espresso.IdlingResource; import android.support.test.rule.ActivityTestRule; import com.jakewharton.espresso.OkHttp3IdlingResource; import com.photoviewer.di.TestsModule; import com.photoviewer.presentation.PhotoViewerApplication; import javax.inject.Inject; import okhttp3.OkHttpClient; import org.junit.Rule; package com.photoviewer.common.steps; public class PageObject<T extends Activity> { @Rule public ActivityTestRule<T> mActivityRule; @Inject OkHttpClient mOkHttpClient; private T mActivity; private IdlingResource mOkHttp3IdlingResource; public PageObject(Class<T> activityClass) { mActivityRule = new ActivityTestRule<>(activityClass, false, false); injectFieldsFromApp(); setUpIdlingResources(); } private void injectFieldsFromApp() {
PhotoViewerApplication.getScopedGraph(new TestsModule()).inject(this);
lifedemons/photoviewer
app/src/androidTest/java/com/photoviewer/common/steps/PageObject.java
// Path: app/src/androidTest/java/com/photoviewer/di/TestsModule.java // @Module(injects = { PageObject.class, PhotosListPage.class }, addsTo = AppModule.class) // public class TestsModule { // } // // Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // }
import android.app.Activity; import android.support.test.espresso.Espresso; import android.support.test.espresso.IdlingResource; import android.support.test.rule.ActivityTestRule; import com.jakewharton.espresso.OkHttp3IdlingResource; import com.photoviewer.di.TestsModule; import com.photoviewer.presentation.PhotoViewerApplication; import javax.inject.Inject; import okhttp3.OkHttpClient; import org.junit.Rule;
package com.photoviewer.common.steps; public class PageObject<T extends Activity> { @Rule public ActivityTestRule<T> mActivityRule; @Inject OkHttpClient mOkHttpClient; private T mActivity; private IdlingResource mOkHttp3IdlingResource; public PageObject(Class<T> activityClass) { mActivityRule = new ActivityTestRule<>(activityClass, false, false); injectFieldsFromApp(); setUpIdlingResources(); } private void injectFieldsFromApp() {
// Path: app/src/androidTest/java/com/photoviewer/di/TestsModule.java // @Module(injects = { PageObject.class, PhotosListPage.class }, addsTo = AppModule.class) // public class TestsModule { // } // // Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java // public class PhotoViewerApplication extends Application { // // @Override // public void onCreate() { // super.onCreate(); // sObjectGraph = ObjectGraph.create(new AppModule(this)); // } // // private static ObjectGraph sObjectGraph; // // public static ObjectGraph getScopedGraph(Object... modules) { // return sObjectGraph.plus(modules); // } // } // Path: app/src/androidTest/java/com/photoviewer/common/steps/PageObject.java import android.app.Activity; import android.support.test.espresso.Espresso; import android.support.test.espresso.IdlingResource; import android.support.test.rule.ActivityTestRule; import com.jakewharton.espresso.OkHttp3IdlingResource; import com.photoviewer.di.TestsModule; import com.photoviewer.presentation.PhotoViewerApplication; import javax.inject.Inject; import okhttp3.OkHttpClient; import org.junit.Rule; package com.photoviewer.common.steps; public class PageObject<T extends Activity> { @Rule public ActivityTestRule<T> mActivityRule; @Inject OkHttpClient mOkHttpClient; private T mActivity; private IdlingResource mOkHttp3IdlingResource; public PageObject(Class<T> activityClass) { mActivityRule = new ActivityTestRule<>(activityClass, false, false); injectFieldsFromApp(); setUpIdlingResources(); } private void injectFieldsFromApp() {
PhotoViewerApplication.getScopedGraph(new TestsModule()).inject(this);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> {
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> {
private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter
private PhotoStatistics mPhotoStatistics;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics;
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics;
@Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics; @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource;
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics; @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource;
@Inject public SavePhotoStatistics(@Named(RxModule.COMPUTATION) Scheduler executionScheduler,
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics; @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource; @Inject public SavePhotoStatistics(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler) { super(executionScheduler, observingScheduler); mPhotoStatisticsToPhotoStatisticsEntityTransformer = new PhotoStatisticsToPhotoStatisticsEntity(); } @Override protected Observable<Void> call() {
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java // public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { // // @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; // // @Override // public Observable<PhotoStatisticsEntity> readStatistics() { // return mStatisticsEntityStore.readStatistics(); // } // // @Override // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return mStatisticsEntityStore.updateStatistics(photoStatisticsEntity); // } // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java // public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { // @Override // public PhotoStatisticsEntity transform(PhotoStatistics from) { // PhotoStatisticsEntity transformed = new PhotoStatisticsEntity(); // // Photo lastOpenedPhoto = from.getLastOpenedPhoto(); // transformed.setLastOpenedPhotoId(lastOpenedPhoto != null ? lastOpenedPhoto.getId() : 0); // transformed.setOpenedPhotosCount(from.getOpenedPhotosCount()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SavePhotoStatistics.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.PhotoStatisticsEntityDataSource; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.photostatisctics.PhotoStatisticsToPhotoStatisticsEntity; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SavePhotoStatistics extends UseCase<Void> { private final PhotoStatisticsToPhotoStatisticsEntity mPhotoStatisticsToPhotoStatisticsEntityTransformer; @Setter private PhotoStatistics mPhotoStatistics; @Inject PhotoStatisticsEntityDataSource mPhotoStatisticsEntityDataSource; @Inject public SavePhotoStatistics(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler) { super(executionScheduler, observingScheduler); mPhotoStatisticsToPhotoStatisticsEntityTransformer = new PhotoStatisticsToPhotoStatisticsEntity(); } @Override protected Observable<Void> call() {
PhotoStatisticsEntity photoStatisticsEntity = mPhotoStatisticsToPhotoStatisticsEntityTransformer.transform(mPhotoStatistics);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/mapper/photostatistics/PhotoStatisticsModelToPhotoStatistics.java
// Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoModelToPhoto.java // public class PhotoModelToPhoto extends BaseLayerDataTransformer<PhotoModel, Photo> { // @Override // public Photo transform(PhotoModel from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // transformed.setUrl(from.getUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // }
import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.mapper.photo.PhotoModelToPhoto; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.model.PhotoStatisticsModel; import com.photoviewer.domain.mapper.BaseLayerDataTransformer;
package com.photoviewer.presentation.mapper.photostatistics; public class PhotoStatisticsModelToPhotoStatistics extends BaseLayerDataTransformer<PhotoStatisticsModel, PhotoStatistics> { private PhotoModelToPhoto mPhotoModelToPhotoTransformer; public PhotoStatisticsModelToPhotoStatistics() { mPhotoModelToPhotoTransformer = new PhotoModelToPhoto(); } @Override public PhotoStatistics transform(PhotoStatisticsModel from) { PhotoStatistics transformed = new PhotoStatistics();
// Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoModelToPhoto.java // public class PhotoModelToPhoto extends BaseLayerDataTransformer<PhotoModel, Photo> { // @Override // public Photo transform(PhotoModel from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // transformed.setUrl(from.getUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // } // Path: app/src/main/java/com/photoviewer/presentation/mapper/photostatistics/PhotoStatisticsModelToPhotoStatistics.java import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.mapper.photo.PhotoModelToPhoto; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.model.PhotoStatisticsModel; import com.photoviewer.domain.mapper.BaseLayerDataTransformer; package com.photoviewer.presentation.mapper.photostatistics; public class PhotoStatisticsModelToPhotoStatistics extends BaseLayerDataTransformer<PhotoStatisticsModel, PhotoStatistics> { private PhotoModelToPhoto mPhotoModelToPhotoTransformer; public PhotoStatisticsModelToPhotoStatistics() { mPhotoModelToPhotoTransformer = new PhotoModelToPhoto(); } @Override public PhotoStatistics transform(PhotoStatisticsModel from) { PhotoStatistics transformed = new PhotoStatistics();
PhotoModel lastOpenedPhotoModel = from.getLastOpenedPhotoModel();
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.domain.Photo; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.BaseLayerDataTransformer;
package com.photoviewer.domain.mapper.photostatisctics; public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { @Override public PhotoStatisticsEntity transform(PhotoStatistics from) { PhotoStatisticsEntity transformed = new PhotoStatisticsEntity();
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // } // Path: app/src/main/java/com/photoviewer/domain/mapper/photostatisctics/PhotoStatisticsToPhotoStatisticsEntity.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.domain.Photo; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.domain.mapper.BaseLayerDataTransformer; package com.photoviewer.domain.mapper.photostatisctics; public class PhotoStatisticsToPhotoStatisticsEntity extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsEntity> { @Override public PhotoStatisticsEntity transform(PhotoStatistics from) { PhotoStatisticsEntity transformed = new PhotoStatisticsEntity();
Photo lastOpenedPhoto = from.getLastOpenedPhoto();
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/db/DatabaseManager.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // }
import android.content.Context; import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.support.ConnectionSource; import com.photoviewer.data.entity.PhotoEntity; import java.sql.SQLException; import javax.inject.Inject;
package com.photoviewer.data.db; public class DatabaseManager { public static final String LOG_TAG_DB = "Photos:Database"; public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; private final ConnectionSource mConnectionSource; //DAOs
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java import android.content.Context; import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.support.ConnectionSource; import com.photoviewer.data.entity.PhotoEntity; import java.sql.SQLException; import javax.inject.Inject; package com.photoviewer.data.db; public class DatabaseManager { public static final String LOG_TAG_DB = "Photos:Database"; public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; private final ConnectionSource mConnectionSource; //DAOs
private Dao<PhotoEntity, Integer> mPhotosDao;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/network/PhotoRestService.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // }
import com.photoviewer.data.entity.PhotoEntity; import java.util.List; import retrofit2.http.GET; import rx.Observable;
package com.photoviewer.data.network; /** * RestApi for retrieving data from the network. */ public interface PhotoRestService { /** * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. */ @GET("/photos")
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // Path: app/src/main/java/com/photoviewer/data/network/PhotoRestService.java import com.photoviewer.data.entity.PhotoEntity; import java.util.List; import retrofit2.http.GET; import rx.Observable; package com.photoviewer.data.network; /** * RestApi for retrieving data from the network. */ public interface PhotoRestService { /** * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. */ @GET("/photos")
Observable<List<PhotoEntity>> photoEntityList();
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/repository/datastore/ServerPhotoEntityStore.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/network/PhotoRestService.java // public interface PhotoRestService { // // /** // * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // @GET("/photos") // Observable<List<PhotoEntity>> photoEntityList(); // }
import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.network.PhotoRestService; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.photoviewer.data.repository.datastore; public class ServerPhotoEntityStore { private final PhotoRestService mService; @Inject public ServerPhotoEntityStore(PhotoRestService service) { mService = service; }
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/network/PhotoRestService.java // public interface PhotoRestService { // // /** // * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // @GET("/photos") // Observable<List<PhotoEntity>> photoEntityList(); // } // Path: app/src/main/java/com/photoviewer/data/repository/datastore/ServerPhotoEntityStore.java import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.network.PhotoRestService; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.photoviewer.data.repository.datastore; public class ServerPhotoEntityStore { private final PhotoRestService mService; @Inject public ServerPhotoEntityStore(PhotoRestService service) { mService = service; }
public Observable<List<PhotoEntity>> photoEntityList() {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject;
package com.photoviewer.presentation.presenter; /** * {@link Presenter} that controls communication between views and models of the presentation * layer. */ public class PhotoDetailsPresenter extends SimplePresenter { private final GetPhotoDetails mGetPhotoDetailsUseCase;
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject; package com.photoviewer.presentation.presenter; /** * {@link Presenter} that controls communication between views and models of the presentation * layer. */ public class PhotoDetailsPresenter extends SimplePresenter { private final GetPhotoDetails mGetPhotoDetailsUseCase;
private final PhotoToPhotoModel mPhotoModelTransformer;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject;
package com.photoviewer.presentation.presenter; /** * {@link Presenter} that controls communication between views and models of the presentation * layer. */ public class PhotoDetailsPresenter extends SimplePresenter { private final GetPhotoDetails mGetPhotoDetailsUseCase; private final PhotoToPhotoModel mPhotoModelTransformer; /** * id used to retrieve photo details */ private int mPhotoId;
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject; package com.photoviewer.presentation.presenter; /** * {@link Presenter} that controls communication between views and models of the presentation * layer. */ public class PhotoDetailsPresenter extends SimplePresenter { private final GetPhotoDetails mGetPhotoDetailsUseCase; private final PhotoToPhotoModel mPhotoModelTransformer; /** * id used to retrieve photo details */ private int mPhotoId;
private PhotoDetailsView mViewDetailsView;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject;
* Loads photo details. */ private void loadPhotoDetails() { hideViewRetry(); showViewLoading(); getPhotoDetails(); } private void showViewLoading() { mViewDetailsView.showLoading(); } private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); }
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject; * Loads photo details. */ private void loadPhotoDetails() { hideViewRetry(); showViewLoading(); getPhotoDetails(); } private void showViewLoading() { mViewDetailsView.showLoading(); } private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); }
private void showPhotoDetailsInView(Photo photo) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject;
*/ private void loadPhotoDetails() { hideViewRetry(); showViewLoading(); getPhotoDetails(); } private void showViewLoading() { mViewDetailsView.showLoading(); } private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); } private void showPhotoDetailsInView(Photo photo) {
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject; */ private void loadPhotoDetails() { hideViewRetry(); showViewLoading(); getPhotoDetails(); } private void showViewLoading() { mViewDetailsView.showLoading(); } private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); } private void showPhotoDetailsInView(Photo photo) {
final PhotoModel photoModel = mPhotoModelTransformer.transform(photo);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject;
} private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); } private void showPhotoDetailsInView(Photo photo) { final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); mViewDetailsView.renderPhoto(photoModel); } private void getPhotoDetails() { mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); }
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java // @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { // // @Setter private int mPhotoId; // private final PhotoEntityToPhoto mPhotoTransformer; // // private PhotoEntityDataSource mPhotoEntityDataSource; // // @Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler, // @Named(RxModule.MAIN_THREAD) Scheduler observingScheduler, // PhotoEntityDataSource photoEntityDataSource) { // super(executionScheduler, observingScheduler); // mPhotoTransformer = new PhotoEntityToPhoto(); // mPhotoEntityDataSource = photoEntityDataSource; // } // // @Override protected Observable<Photo> call() { // return this.mPhotoEntityDataSource.photo(mPhotoId).map(mPhotoTransformer::transform); // } // } // // Path: app/src/main/java/com/photoviewer/domain/usecases/SimpleSubscriber.java // public class SimpleSubscriber<T> extends rx.Subscriber<T> { // @Override // public void onCompleted() { // // no-op by default. // } // // @Override // public void onError(Throwable e) { // // no-op by default. // } // // @Override // public void onNext(T t) { // // no-op by default. // } // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java import android.support.annotation.NonNull; import com.photoviewer.domain.Photo; import com.photoviewer.domain.usecases.GetPhotoDetails; import com.photoviewer.domain.usecases.SimpleSubscriber; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.PhotoDetailsView; import javax.inject.Inject; } private void hideViewLoading() { mViewDetailsView.hideLoading(); } private void showViewRetry() { mViewDetailsView.showRetry(); } private void hideViewRetry() { mViewDetailsView.hideRetry(); } private void showErrorMessage() { //TODO implement String errorMessage = "Error happened"; mViewDetailsView.showError(errorMessage); } private void showPhotoDetailsInView(Photo photo) { final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); mViewDetailsView.renderPhoto(photoModel); } private void getPhotoDetails() { mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); }
private final class PhotoDetailsSubscriber extends SimpleSubscriber<Photo> {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId;
private final PhotoEntityToPhoto mPhotoTransformer;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId; private final PhotoEntityToPhoto mPhotoTransformer;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId; private final PhotoEntityToPhoto mPhotoTransformer;
private PhotoEntityDataSource mPhotoEntityDataSource;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId; private final PhotoEntityToPhoto mPhotoTransformer; private PhotoEntityDataSource mPhotoEntityDataSource;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/GetPhotoDetails.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class GetPhotoDetails extends UseCase<Photo> { @Setter private int mPhotoId; private final PhotoEntityToPhoto mPhotoTransformer; private PhotoEntityDataSource mPhotoEntityDataSource;
@Inject public GetPhotoDetails(@Named(RxModule.COMPUTATION) Scheduler executionScheduler,
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/navigation/Navigator.java
// Path: app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java // public class PhotoDetailsActivity extends DiAppCompatActivity implements PhotoDetailsView { // // private static final String INTENT_EXTRA_PARAM_PHOTO_ID = "INTENT_PARAM_PHOTO_ID"; // private static final String INSTANCE_STATE_PARAM_PHOTO_ID = "STATE_PARAM_PHOTO_ID"; // // @Inject PhotoDetailsPresenter mPhotoDetailsPresenter; // @Inject Picasso mPicasso; // // //Content Views // @BindView(R.id.cover_image_view) ImageView mCoverImageView; // @BindView(R.id.title_text_view) TextView mTitleTextView; // // //Data Loading Views // @BindView(R.id.progress_layout) RelativeLayout mProgressView; // @BindView(R.id.retry_layout) RelativeLayout mRetryView; // @BindView(R.id.retry_button) Button mRetryButton; // // private int mPhotoId; // // public static Intent getCallingIntent(Context context, int photoId) { // Intent callingIntent = new Intent(context, PhotoDetailsActivity.class); // callingIntent.putExtra(INTENT_EXTRA_PARAM_PHOTO_ID, photoId); // // return callingIntent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // setContentView(R.layout.activity_photo_details); // // initialize(savedInstanceState); // setUpUI(); // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // if (outState != null) { // outState.putInt(INSTANCE_STATE_PARAM_PHOTO_ID, mPhotoId); // } // super.onSaveInstanceState(outState); // } // // /** // * Initializes this activity. // */ // private void initialize(Bundle savedInstanceState) { // if (savedInstanceState == null) { // this.mPhotoId = getIntent().getIntExtra(INTENT_EXTRA_PARAM_PHOTO_ID, -1); // } else { // this.mPhotoId = savedInstanceState.getInt(INSTANCE_STATE_PARAM_PHOTO_ID); // } // mPhotoDetailsPresenter.setView(this); // mPhotoDetailsPresenter.initialize(mPhotoId); // } // // private void setUpUI() { // // setSupportActionBar(mToolbar); // // mRetryButton.setOnClickListener(v -> onButtonRetryClick()); // } // // @Override // public void onResume() { // super.onResume(); // this.mPhotoDetailsPresenter.resume(); // } // // @Override // public void onPause() { // super.onPause(); // mPhotoDetailsPresenter.pause(); // } // // @Override // public void onDestroy() { // super.onDestroy(); // mPhotoDetailsPresenter.destroy(); // } // // @Override // public void showLoading() { // mProgressView.setVisibility(View.VISIBLE); // setProgressBarIndeterminateVisibility(true); // } // // @Override // public void hideLoading() { // mProgressView.setVisibility(View.GONE); // setProgressBarIndeterminateVisibility(false); // } // // @Override // public void showRetry() { // mRetryView.setVisibility(View.VISIBLE); // } // // @Override // public void hideRetry() { // mRetryView.setVisibility(View.GONE); // } // // @Override // public void showError(String message) { // showToastMessage(message); // } // // private void showToastMessage(String message) { // Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // } // // /** // * Loads all photos. // */ // private void loadPhotoDetails() { // if (mPhotoDetailsPresenter != null) { // mPhotoDetailsPresenter.initialize(mPhotoId); // } // } // // void onButtonRetryClick() { // loadPhotoDetails(); // } // // @Override // public void renderPhoto(PhotoModel photoModel) { // if (photoModel != null) { // mPicasso.load(photoModel.getUrl()) // .placeholder(R.drawable.ic_crop_original_black) // .error(R.drawable.ic_error_outline_black) // .into(mCoverImageView); // mTitleTextView.setText(photoModel.getTitle()); // } // } // }
import android.content.Context; import android.content.Intent; import com.photoviewer.presentation.view.activity.PhotoDetailsActivity; import javax.inject.Inject;
package com.photoviewer.presentation.navigation; /** * Class used to navigate through the application. */ public class Navigator { @Inject public Navigator() {} /** * Goes to the photo details screen. * * @param context A Context needed to open the activity. */ public void navigateToPhotoDetails(Context context, int photoId) { if (context != null) {
// Path: app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java // public class PhotoDetailsActivity extends DiAppCompatActivity implements PhotoDetailsView { // // private static final String INTENT_EXTRA_PARAM_PHOTO_ID = "INTENT_PARAM_PHOTO_ID"; // private static final String INSTANCE_STATE_PARAM_PHOTO_ID = "STATE_PARAM_PHOTO_ID"; // // @Inject PhotoDetailsPresenter mPhotoDetailsPresenter; // @Inject Picasso mPicasso; // // //Content Views // @BindView(R.id.cover_image_view) ImageView mCoverImageView; // @BindView(R.id.title_text_view) TextView mTitleTextView; // // //Data Loading Views // @BindView(R.id.progress_layout) RelativeLayout mProgressView; // @BindView(R.id.retry_layout) RelativeLayout mRetryView; // @BindView(R.id.retry_button) Button mRetryButton; // // private int mPhotoId; // // public static Intent getCallingIntent(Context context, int photoId) { // Intent callingIntent = new Intent(context, PhotoDetailsActivity.class); // callingIntent.putExtra(INTENT_EXTRA_PARAM_PHOTO_ID, photoId); // // return callingIntent; // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // setContentView(R.layout.activity_photo_details); // // initialize(savedInstanceState); // setUpUI(); // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // if (outState != null) { // outState.putInt(INSTANCE_STATE_PARAM_PHOTO_ID, mPhotoId); // } // super.onSaveInstanceState(outState); // } // // /** // * Initializes this activity. // */ // private void initialize(Bundle savedInstanceState) { // if (savedInstanceState == null) { // this.mPhotoId = getIntent().getIntExtra(INTENT_EXTRA_PARAM_PHOTO_ID, -1); // } else { // this.mPhotoId = savedInstanceState.getInt(INSTANCE_STATE_PARAM_PHOTO_ID); // } // mPhotoDetailsPresenter.setView(this); // mPhotoDetailsPresenter.initialize(mPhotoId); // } // // private void setUpUI() { // // setSupportActionBar(mToolbar); // // mRetryButton.setOnClickListener(v -> onButtonRetryClick()); // } // // @Override // public void onResume() { // super.onResume(); // this.mPhotoDetailsPresenter.resume(); // } // // @Override // public void onPause() { // super.onPause(); // mPhotoDetailsPresenter.pause(); // } // // @Override // public void onDestroy() { // super.onDestroy(); // mPhotoDetailsPresenter.destroy(); // } // // @Override // public void showLoading() { // mProgressView.setVisibility(View.VISIBLE); // setProgressBarIndeterminateVisibility(true); // } // // @Override // public void hideLoading() { // mProgressView.setVisibility(View.GONE); // setProgressBarIndeterminateVisibility(false); // } // // @Override // public void showRetry() { // mRetryView.setVisibility(View.VISIBLE); // } // // @Override // public void hideRetry() { // mRetryView.setVisibility(View.GONE); // } // // @Override // public void showError(String message) { // showToastMessage(message); // } // // private void showToastMessage(String message) { // Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // } // // /** // * Loads all photos. // */ // private void loadPhotoDetails() { // if (mPhotoDetailsPresenter != null) { // mPhotoDetailsPresenter.initialize(mPhotoId); // } // } // // void onButtonRetryClick() { // loadPhotoDetails(); // } // // @Override // public void renderPhoto(PhotoModel photoModel) { // if (photoModel != null) { // mPicasso.load(photoModel.getUrl()) // .placeholder(R.drawable.ic_crop_original_black) // .error(R.drawable.ic_error_outline_black) // .into(mCoverImageView); // mTitleTextView.setText(photoModel.getTitle()); // } // } // } // Path: app/src/main/java/com/photoviewer/presentation/navigation/Navigator.java import android.content.Context; import android.content.Intent; import com.photoviewer.presentation.view.activity.PhotoDetailsActivity; import javax.inject.Inject; package com.photoviewer.presentation.navigation; /** * Class used to navigate through the application. */ public class Navigator { @Inject public Navigator() {} /** * Goes to the photo details screen. * * @param context A Context needed to open the activity. */ public void navigateToPhotoDetails(Context context, int photoId) { if (context != null) {
Intent intentToLaunch = PhotoDetailsActivity.getCallingIntent(context, photoId);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle;
private PhotoEntityDataSource mPhotoEntityDataSource;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle; private PhotoEntityDataSource mPhotoEntityDataSource;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle; private PhotoEntityDataSource mPhotoEntityDataSource;
private final PhotoEntityToPhoto photoTransformer;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // }
import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler;
package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle; private PhotoEntityDataSource mPhotoEntityDataSource; private final PhotoEntityToPhoto photoTransformer;
// Path: app/src/main/java/com/photoviewer/data/repository/PhotoEntityDataSource.java // public class PhotoEntityDataSource implements PhotoRepository { // // private DatabasePhotoEntityStore mDatabasePhotoEntityStore; // private ServerPhotoEntityStore mServerPhotoEntityStore; // // @Inject // public PhotoEntityDataSource(DatabasePhotoEntityStore databasePhotoEntityStore, ServerPhotoEntityStore serverPhotoEntityStore) { // mDatabasePhotoEntityStore = databasePhotoEntityStore; // mServerPhotoEntityStore = serverPhotoEntityStore; // } // // @Override // public Observable<List<PhotoEntity>> photos() { // return Observable.create(new Observable.OnSubscribe<List<PhotoEntity>>() { // @Override // public void call(Subscriber<? super List<PhotoEntity>> subscriber) { // queryDatabaseForAll(subscriber); // } // }); // } // // @Override // public Observable<List<PhotoEntity>> searchPhotosByTitle(String title) { // return mDatabasePhotoEntityStore.queryForTitle(title); // } // // @Override // public Observable<PhotoEntity> photo(int photoId) { // return mDatabasePhotoEntityStore.queryForId(photoId); // } // // private void queryDatabaseForAll(final Subscriber<? super List<PhotoEntity>> subscriber) { // mDatabasePhotoEntityStore.queryForAll().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // fetchServerForAll(subscriber); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // if (photoEntities.size() != 0) { // subscriber.onNext(photoEntities); // subscriber.onCompleted(); // } else { // fetchServerForAll(subscriber); // } // } // }); // } // // private void fetchServerForAll(Subscriber<? super List<PhotoEntity>> subscriber) { // mServerPhotoEntityStore.photoEntityList().subscribe(new Observer<List<PhotoEntity>>() { // @Override // public void onCompleted() { // subscriber.onCompleted(); // } // // @Override // public void onError(Throwable e) { // subscriber.onError(e); // } // // @Override // public void onNext(List<PhotoEntity> photoEntities) { // subscriber.onNext(photoEntities); // mDatabasePhotoEntityStore. // saveAll(photoEntities). // subscribe(); // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/photo/PhotoEntityToPhoto.java // public class PhotoEntityToPhoto extends BaseLayerDataTransformer<PhotoEntity, Photo> { // @Override // public Photo transform(PhotoEntity from) { // Photo transformed = new Photo(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/di/modules/RxModule.java // @Module(library = true, complete = false) public class RxModule { // // public static final String COMPUTATION = "computation"; // public static final String IO = "io"; // public static final String MAIN_THREAD = "main_thread"; // // @Provides @Singleton @Named(IO) Scheduler provideIoScheduler() { // return Schedulers.io(); // } // // @Provides @Singleton @Named(MAIN_THREAD) Scheduler provideMainScheduler() { // return AndroidSchedulers.mainThread(); // } // // @Provides @Singleton @Named(COMPUTATION) Scheduler provideComputationScheduler() { // return Schedulers.computation(); // } // } // Path: app/src/main/java/com/photoviewer/domain/usecases/SearchByTitle.java import com.photoviewer.data.repository.PhotoEntityDataSource; import com.photoviewer.domain.Photo; import com.photoviewer.domain.mapper.photo.PhotoEntityToPhoto; import com.photoviewer.presentation.di.modules.RxModule; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import lombok.Setter; import lombok.experimental.Accessors; import rx.Observable; import rx.Scheduler; package com.photoviewer.domain.usecases; @Accessors(prefix = "m") public class SearchByTitle extends UseCase<List<Photo>> { @Setter private String mSearchedTitle; private PhotoEntityDataSource mPhotoEntityDataSource; private final PhotoEntityToPhoto photoTransformer;
@Inject public SearchByTitle(@Named(RxModule.COMPUTATION) Scheduler executionScheduler,
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/mapper/photostatistics/PhotoStatisticsToPhotoStatisticsModel.java
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // }
import com.photoviewer.domain.Photo; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoStatisticsModel; import com.photoviewer.domain.mapper.BaseLayerDataTransformer;
package com.photoviewer.presentation.mapper.photostatistics; public class PhotoStatisticsToPhotoStatisticsModel extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsModel> { private PhotoToPhotoModel mPhotoToPhotoModelTransformer; public PhotoStatisticsToPhotoStatisticsModel() { mPhotoToPhotoModelTransformer = new PhotoToPhotoModel(); } @Override public PhotoStatisticsModel transform(PhotoStatistics from) { PhotoStatisticsModel transformed = new PhotoStatisticsModel(); transformed.setOpenedPhotosCount(from.getOpenedPhotosCount());
// Path: app/src/main/java/com/photoviewer/domain/Photo.java // @Accessors(prefix = "m") // public class Photo { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/domain/PhotoStatistics.java // @Accessors(prefix = "m") // public class PhotoStatistics { // // @Setter // @Getter // private Photo mLastOpenedPhoto; // // @Setter // @Getter // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/presentation/mapper/photo/PhotoToPhotoModel.java // public class PhotoToPhotoModel extends BaseLayerDataTransformer<Photo, PhotoModel> { // @Override // public PhotoModel transform(Photo from) { // PhotoModel transformed = new PhotoModel(); // // transformed.setId(from.getId()); // transformed.setTitle(from.getTitle()); // transformed.setUrl(from.getUrl()); // transformed.setThumbnailUrl(from.getThumbnailUrl()); // // return transformed; // } // } // // Path: app/src/main/java/com/photoviewer/presentation/model/PhotoStatisticsModel.java // @Accessors(prefix = "m") // public class PhotoStatisticsModel { // // @Setter // @Getter // private PhotoModel mLastOpenedPhotoModel; // // @Setter // @Getter // private int mOpenedPhotosCount; // // public void incOpenedPhotosCount() { // mOpenedPhotosCount++; // } // } // // Path: app/src/main/java/com/photoviewer/domain/mapper/BaseLayerDataTransformer.java // public abstract class BaseLayerDataTransformer<F, T> implements LayerDataTransformer<F, T> { // // @Override // public List<T> transform(Collection<F> from) { // List<T> transformed = new ArrayList<>(from.size()); // // for (F fromObject : from) { // transformed.add(transform(fromObject)); // } // // return transformed; // } // } // Path: app/src/main/java/com/photoviewer/presentation/mapper/photostatistics/PhotoStatisticsToPhotoStatisticsModel.java import com.photoviewer.domain.Photo; import com.photoviewer.domain.PhotoStatistics; import com.photoviewer.presentation.mapper.photo.PhotoToPhotoModel; import com.photoviewer.presentation.model.PhotoStatisticsModel; import com.photoviewer.domain.mapper.BaseLayerDataTransformer; package com.photoviewer.presentation.mapper.photostatistics; public class PhotoStatisticsToPhotoStatisticsModel extends BaseLayerDataTransformer<PhotoStatistics, PhotoStatisticsModel> { private PhotoToPhotoModel mPhotoToPhotoModelTransformer; public PhotoStatisticsToPhotoStatisticsModel() { mPhotoToPhotoModelTransformer = new PhotoToPhotoModel(); } @Override public PhotoStatisticsModel transform(PhotoStatistics from) { PhotoStatisticsModel transformed = new PhotoStatisticsModel(); transformed.setOpenedPhotosCount(from.getOpenedPhotosCount());
Photo lastOpenedPhoto = from.getLastOpenedPhoto();
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // }
import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException;
package com.photoviewer.data.db.migrations; public class CreatePhotosTable extends Migration { @Override public void up(SQLiteDatabase db, ConnectionSource connectionSource) { try {
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // } // Path: app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; package com.photoviewer.data.db.migrations; public class CreatePhotosTable extends Migration { @Override public void up(SQLiteDatabase db, ConnectionSource connectionSource) { try {
TableUtils.createTable(connectionSource, PhotoEntity.class);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // }
import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException;
package com.photoviewer.data.db.migrations; public class CreatePhotosTable extends Migration { @Override public void up(SQLiteDatabase db, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, PhotoEntity.class); } catch (SQLException e) {
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoEntity.java // @Accessors(prefix = "m") // @DatabaseTable(tableName = "photos") // public class PhotoEntity { // // public interface Fields { // String ID = "id"; // String ALBUM_ID = "albumId"; // String TITLE = "title"; // String URL = "url"; // String THUMBNAIL_URL = "thumbnailUrl"; // } // // @SerializedName(Fields.ID) // @Getter // @Setter // @DatabaseField(id = true, columnName = Fields.ID) // private int mId; // // @SerializedName(Fields.ALBUM_ID) // @Getter // @DatabaseField(columnName = Fields.ALBUM_ID) // private int mAlbumId; // // @SerializedName(Fields.TITLE) // @Getter // @Setter // @DatabaseField(columnName = Fields.TITLE) // private String mTitle; // // @SerializedName(Fields.URL) // @Getter // @DatabaseField(columnName = Fields.URL) // private String mUrl; // // @SerializedName(Fields.THUMBNAIL_URL) // @Getter // @DatabaseField(columnName = Fields.THUMBNAIL_URL) // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/data/db/DatabaseManager.java // public class DatabaseManager { // // public static final String LOG_TAG_DB = "Photos:Database"; // public static final String DEFAULT_DATABASE_NAME = "photo_viewer"; // // private final ConnectionSource mConnectionSource; // // //DAOs // private Dao<PhotoEntity, Integer> mPhotosDao; // // @Inject // public DatabaseManager(Context context) { // this(context, DEFAULT_DATABASE_NAME); // } // // public DatabaseManager(Context context, String databaseName) { // DatabaseHelper databaseHelper = new DatabaseHelper(context, databaseName); // mConnectionSource = databaseHelper.getConnectionSource(); // force database creation/upgrade eagerly // } // // public Dao<PhotoEntity, Integer> getPhotosDao() { // if (mPhotosDao == null) { // createPhotoEntityDao(); // } // // return mPhotosDao; // } // // private void createPhotoEntityDao() { // try { // mPhotosDao = DaoManager.createDao(mConnectionSource, PhotoEntity.class); // mPhotosDao.setObjectCache(true); // } catch (SQLException e) { // Log.wtf(LOG_TAG_DB, "Creation of Dao<" + PhotoEntity.class + "> failed", e); // } // } // } // Path: app/src/main/java/com/photoviewer/data/db/migrations/CreatePhotosTable.java import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.photoviewer.data.entity.PhotoEntity; import com.photoviewer.data.db.DatabaseManager; import java.sql.SQLException; package com.photoviewer.data.db.migrations; public class CreatePhotosTable extends Migration { @Override public void up(SQLiteDatabase db, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, PhotoEntity.class); } catch (SQLException e) {
Log.wtf(DatabaseManager.LOG_TAG_DB, "Creation of PhotosTable failed", e);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/di/modules/ApiModule.java
// Path: app/src/main/java/com/photoviewer/data/network/PhotoRestService.java // public interface PhotoRestService { // // /** // * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // @GET("/photos") // Observable<List<PhotoEntity>> photoEntityList(); // }
import android.content.Context; import com.jakewharton.picasso.OkHttp3Downloader; import com.photoviewer.BuildConfig; import com.photoviewer.data.network.PhotoRestService; import com.squareup.picasso.Picasso; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class ApiModule { private static String API_BASE_URL = "http://jsonplaceholder.typicode.com";
// Path: app/src/main/java/com/photoviewer/data/network/PhotoRestService.java // public interface PhotoRestService { // // /** // * Retrieves an {@link rx.Observable} which will emit a List of {@link PhotoEntity}. // */ // @GET("/photos") // Observable<List<PhotoEntity>> photoEntityList(); // } // Path: app/src/main/java/com/photoviewer/presentation/di/modules/ApiModule.java import android.content.Context; import com.jakewharton.picasso.OkHttp3Downloader; import com.photoviewer.BuildConfig; import com.photoviewer.data.network.PhotoRestService; import com.squareup.picasso.Picasso; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.photoviewer.presentation.di.modules; @Module(library = true, complete = false) public class ApiModule { private static String API_BASE_URL = "http://jsonplaceholder.typicode.com";
@Provides @Singleton PhotoRestService provideOrderRatingService(OkHttpClient httpClient) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/adapter/PhotoAdapter.java
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/utils/ImageRoundedCornersTransformation.java // public class ImageRoundedCornersTransformation implements // com.squareup.picasso.Transformation { // private final int radius; // private final int margin; // // // radius is corner radius in dp // // margin is the board in dp // public ImageRoundedCornersTransformation(final int radius, final int margin) { // this.radius = radius; // this.margin = margin; // } // // @Override // public Bitmap transform(final Bitmap source) { // final Paint paint = new Paint(); // paint.setAntiAlias(true); // paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, // Shader.TileMode.CLAMP)); // // Bitmap output = Bitmap.createBitmap(source.getWidth(), // source.getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(output); // canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() // - margin, source.getHeight() - margin), radius, radius, paint); // // if (source != output) { // source.recycle(); // } // // return output; // } // // @Override // public String key() { // return "rounded"; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.utils.ImageRoundedCornersTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.Collection; import java.util.List;
package com.photoviewer.presentation.view.adapter; /** * Adapter that manages a collection of {@link PhotoModel}. */ public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> { private final LayoutInflater mLayoutInflater; private final Context mContext; private final Picasso mPicasso;
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/utils/ImageRoundedCornersTransformation.java // public class ImageRoundedCornersTransformation implements // com.squareup.picasso.Transformation { // private final int radius; // private final int margin; // // // radius is corner radius in dp // // margin is the board in dp // public ImageRoundedCornersTransformation(final int radius, final int margin) { // this.radius = radius; // this.margin = margin; // } // // @Override // public Bitmap transform(final Bitmap source) { // final Paint paint = new Paint(); // paint.setAntiAlias(true); // paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, // Shader.TileMode.CLAMP)); // // Bitmap output = Bitmap.createBitmap(source.getWidth(), // source.getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(output); // canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() // - margin, source.getHeight() - margin), radius, radius, paint); // // if (source != output) { // source.recycle(); // } // // return output; // } // // @Override // public String key() { // return "rounded"; // } // } // Path: app/src/main/java/com/photoviewer/presentation/view/adapter/PhotoAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.utils.ImageRoundedCornersTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.Collection; import java.util.List; package com.photoviewer.presentation.view.adapter; /** * Adapter that manages a collection of {@link PhotoModel}. */ public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> { private final LayoutInflater mLayoutInflater; private final Context mContext; private final Picasso mPicasso;
private List<PhotoModel> mPhotoModelsList;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/adapter/PhotoAdapter.java
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/utils/ImageRoundedCornersTransformation.java // public class ImageRoundedCornersTransformation implements // com.squareup.picasso.Transformation { // private final int radius; // private final int margin; // // // radius is corner radius in dp // // margin is the board in dp // public ImageRoundedCornersTransformation(final int radius, final int margin) { // this.radius = radius; // this.margin = margin; // } // // @Override // public Bitmap transform(final Bitmap source) { // final Paint paint = new Paint(); // paint.setAntiAlias(true); // paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, // Shader.TileMode.CLAMP)); // // Bitmap output = Bitmap.createBitmap(source.getWidth(), // source.getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(output); // canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() // - margin, source.getHeight() - margin), radius, radius, paint); // // if (source != output) { // source.recycle(); // } // // return output; // } // // @Override // public String key() { // return "rounded"; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.utils.ImageRoundedCornersTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.Collection; import java.util.List;
}); } private void setText(TextView textView, String original) { if (mTextToHighlight != null && !mTextToHighlight.isEmpty()) { String preparedMarkup = String.format(STRING_PREPARED_HIGHLIGHT_MARKUP, mTextToHighlight); String highlighted = original.replaceAll(mTextToHighlight, preparedMarkup); textView.setText(Html.fromHtml(highlighted)); } else { textView.setText(original); } } @Override public long getItemId(int position) { return position; } public void setPhotosCollection(Collection<PhotoModel> photoModelsCollection) { validatePhotosCollection(photoModelsCollection); mPhotoModelsList = (List<PhotoModel>) photoModelsCollection; notifyDataSetChanged(); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } private void setupTransformation() { int radius = (int) mContext.getResources().getDimension(R.dimen.list_view_row_icon_rounding_radius);
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/view/utils/ImageRoundedCornersTransformation.java // public class ImageRoundedCornersTransformation implements // com.squareup.picasso.Transformation { // private final int radius; // private final int margin; // // // radius is corner radius in dp // // margin is the board in dp // public ImageRoundedCornersTransformation(final int radius, final int margin) { // this.radius = radius; // this.margin = margin; // } // // @Override // public Bitmap transform(final Bitmap source) { // final Paint paint = new Paint(); // paint.setAntiAlias(true); // paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, // Shader.TileMode.CLAMP)); // // Bitmap output = Bitmap.createBitmap(source.getWidth(), // source.getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(output); // canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() // - margin, source.getHeight() - margin), radius, radius, paint); // // if (source != output) { // source.recycle(); // } // // return output; // } // // @Override // public String key() { // return "rounded"; // } // } // Path: app/src/main/java/com/photoviewer/presentation/view/adapter/PhotoAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.view.utils.ImageRoundedCornersTransformation; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.Collection; import java.util.List; }); } private void setText(TextView textView, String original) { if (mTextToHighlight != null && !mTextToHighlight.isEmpty()) { String preparedMarkup = String.format(STRING_PREPARED_HIGHLIGHT_MARKUP, mTextToHighlight); String highlighted = original.replaceAll(mTextToHighlight, preparedMarkup); textView.setText(Html.fromHtml(highlighted)); } else { textView.setText(original); } } @Override public long getItemId(int position) { return position; } public void setPhotosCollection(Collection<PhotoModel> photoModelsCollection) { validatePhotosCollection(photoModelsCollection); mPhotoModelsList = (List<PhotoModel>) photoModelsCollection; notifyDataSetChanged(); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } private void setupTransformation() { int radius = (int) mContext.getResources().getDimension(R.dimen.list_view_row_icon_rounding_radius);
mImageTransformation = new ImageRoundedCornersTransformation(radius, 0);
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java // public class PhotoDetailsPresenter extends SimplePresenter { // // private final GetPhotoDetails mGetPhotoDetailsUseCase; // private final PhotoToPhotoModel mPhotoModelTransformer; // /** // * id used to retrieve photo details // */ // private int mPhotoId; // private PhotoDetailsView mViewDetailsView; // // @Inject // public PhotoDetailsPresenter(GetPhotoDetails getPhotoDetailsUseCase) { // mGetPhotoDetailsUseCase = getPhotoDetailsUseCase; // mPhotoModelTransformer = new PhotoToPhotoModel(); // } // // public void setView(@NonNull PhotoDetailsView view) { // mViewDetailsView = view; // } // // @Override // public void destroy() { // mGetPhotoDetailsUseCase.unsubscribe(); // } // // /** // * Initializes the presenter by start retrieving photo details. // */ // public void initialize(int photoId) { // mPhotoId = photoId; // loadPhotoDetails(); // } // // /** // * Loads photo details. // */ // private void loadPhotoDetails() { // hideViewRetry(); // showViewLoading(); // getPhotoDetails(); // } // // private void showViewLoading() { // mViewDetailsView.showLoading(); // } // // private void hideViewLoading() { // mViewDetailsView.hideLoading(); // } // // private void showViewRetry() { // mViewDetailsView.showRetry(); // } // // private void hideViewRetry() { // mViewDetailsView.hideRetry(); // } // // private void showErrorMessage() { // //TODO implement // String errorMessage = "Error happened"; // mViewDetailsView.showError(errorMessage); // } // // private void showPhotoDetailsInView(Photo photo) { // final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); // mViewDetailsView.renderPhoto(photoModel); // } // // private void getPhotoDetails() { // mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); // mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); // } // // private final class PhotoDetailsSubscriber extends SimpleSubscriber<Photo> { // // @Override // public void onCompleted() { // PhotoDetailsPresenter.this.hideViewLoading(); // } // // @Override // public void onError(Throwable e) { // PhotoDetailsPresenter.this.hideViewLoading(); // PhotoDetailsPresenter.this.showErrorMessage(); // PhotoDetailsPresenter.this.showViewRetry(); // } // // @Override // public void onNext(Photo photo) { // PhotoDetailsPresenter.this.showPhotoDetailsInView(photo); // } // } // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.presenter.PhotoDetailsPresenter; import com.photoviewer.presentation.view.PhotoDetailsView; import com.squareup.picasso.Picasso; import javax.inject.Inject;
package com.photoviewer.presentation.view.activity; /** * Activity that shows details of a certain photo. */ public class PhotoDetailsActivity extends DiAppCompatActivity implements PhotoDetailsView { private static final String INTENT_EXTRA_PARAM_PHOTO_ID = "INTENT_PARAM_PHOTO_ID"; private static final String INSTANCE_STATE_PARAM_PHOTO_ID = "STATE_PARAM_PHOTO_ID";
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java // public class PhotoDetailsPresenter extends SimplePresenter { // // private final GetPhotoDetails mGetPhotoDetailsUseCase; // private final PhotoToPhotoModel mPhotoModelTransformer; // /** // * id used to retrieve photo details // */ // private int mPhotoId; // private PhotoDetailsView mViewDetailsView; // // @Inject // public PhotoDetailsPresenter(GetPhotoDetails getPhotoDetailsUseCase) { // mGetPhotoDetailsUseCase = getPhotoDetailsUseCase; // mPhotoModelTransformer = new PhotoToPhotoModel(); // } // // public void setView(@NonNull PhotoDetailsView view) { // mViewDetailsView = view; // } // // @Override // public void destroy() { // mGetPhotoDetailsUseCase.unsubscribe(); // } // // /** // * Initializes the presenter by start retrieving photo details. // */ // public void initialize(int photoId) { // mPhotoId = photoId; // loadPhotoDetails(); // } // // /** // * Loads photo details. // */ // private void loadPhotoDetails() { // hideViewRetry(); // showViewLoading(); // getPhotoDetails(); // } // // private void showViewLoading() { // mViewDetailsView.showLoading(); // } // // private void hideViewLoading() { // mViewDetailsView.hideLoading(); // } // // private void showViewRetry() { // mViewDetailsView.showRetry(); // } // // private void hideViewRetry() { // mViewDetailsView.hideRetry(); // } // // private void showErrorMessage() { // //TODO implement // String errorMessage = "Error happened"; // mViewDetailsView.showError(errorMessage); // } // // private void showPhotoDetailsInView(Photo photo) { // final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); // mViewDetailsView.renderPhoto(photoModel); // } // // private void getPhotoDetails() { // mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); // mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); // } // // private final class PhotoDetailsSubscriber extends SimpleSubscriber<Photo> { // // @Override // public void onCompleted() { // PhotoDetailsPresenter.this.hideViewLoading(); // } // // @Override // public void onError(Throwable e) { // PhotoDetailsPresenter.this.hideViewLoading(); // PhotoDetailsPresenter.this.showErrorMessage(); // PhotoDetailsPresenter.this.showViewRetry(); // } // // @Override // public void onNext(Photo photo) { // PhotoDetailsPresenter.this.showPhotoDetailsInView(photo); // } // } // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.presenter.PhotoDetailsPresenter; import com.photoviewer.presentation.view.PhotoDetailsView; import com.squareup.picasso.Picasso; import javax.inject.Inject; package com.photoviewer.presentation.view.activity; /** * Activity that shows details of a certain photo. */ public class PhotoDetailsActivity extends DiAppCompatActivity implements PhotoDetailsView { private static final String INTENT_EXTRA_PARAM_PHOTO_ID = "INTENT_PARAM_PHOTO_ID"; private static final String INSTANCE_STATE_PARAM_PHOTO_ID = "STATE_PARAM_PHOTO_ID";
@Inject PhotoDetailsPresenter mPhotoDetailsPresenter;
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java // public class PhotoDetailsPresenter extends SimplePresenter { // // private final GetPhotoDetails mGetPhotoDetailsUseCase; // private final PhotoToPhotoModel mPhotoModelTransformer; // /** // * id used to retrieve photo details // */ // private int mPhotoId; // private PhotoDetailsView mViewDetailsView; // // @Inject // public PhotoDetailsPresenter(GetPhotoDetails getPhotoDetailsUseCase) { // mGetPhotoDetailsUseCase = getPhotoDetailsUseCase; // mPhotoModelTransformer = new PhotoToPhotoModel(); // } // // public void setView(@NonNull PhotoDetailsView view) { // mViewDetailsView = view; // } // // @Override // public void destroy() { // mGetPhotoDetailsUseCase.unsubscribe(); // } // // /** // * Initializes the presenter by start retrieving photo details. // */ // public void initialize(int photoId) { // mPhotoId = photoId; // loadPhotoDetails(); // } // // /** // * Loads photo details. // */ // private void loadPhotoDetails() { // hideViewRetry(); // showViewLoading(); // getPhotoDetails(); // } // // private void showViewLoading() { // mViewDetailsView.showLoading(); // } // // private void hideViewLoading() { // mViewDetailsView.hideLoading(); // } // // private void showViewRetry() { // mViewDetailsView.showRetry(); // } // // private void hideViewRetry() { // mViewDetailsView.hideRetry(); // } // // private void showErrorMessage() { // //TODO implement // String errorMessage = "Error happened"; // mViewDetailsView.showError(errorMessage); // } // // private void showPhotoDetailsInView(Photo photo) { // final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); // mViewDetailsView.renderPhoto(photoModel); // } // // private void getPhotoDetails() { // mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); // mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); // } // // private final class PhotoDetailsSubscriber extends SimpleSubscriber<Photo> { // // @Override // public void onCompleted() { // PhotoDetailsPresenter.this.hideViewLoading(); // } // // @Override // public void onError(Throwable e) { // PhotoDetailsPresenter.this.hideViewLoading(); // PhotoDetailsPresenter.this.showErrorMessage(); // PhotoDetailsPresenter.this.showViewRetry(); // } // // @Override // public void onNext(Photo photo) { // PhotoDetailsPresenter.this.showPhotoDetailsInView(photo); // } // } // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.presenter.PhotoDetailsPresenter; import com.photoviewer.presentation.view.PhotoDetailsView; import com.squareup.picasso.Picasso; import javax.inject.Inject;
} @Override public void hideRetry() { mRetryView.setVisibility(View.GONE); } @Override public void showError(String message) { showToastMessage(message); } private void showToastMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } /** * Loads all photos. */ private void loadPhotoDetails() { if (mPhotoDetailsPresenter != null) { mPhotoDetailsPresenter.initialize(mPhotoId); } } void onButtonRetryClick() { loadPhotoDetails(); } @Override
// Path: app/src/main/java/com/photoviewer/presentation/model/PhotoModel.java // @Accessors(prefix = "m") // public class PhotoModel { // // @Getter // @Setter // private int mId; // // @Getter // @Setter // private String mTitle; // // @Getter // @Setter // private String mUrl; // // @Getter // @Setter // private String mThumbnailUrl; // } // // Path: app/src/main/java/com/photoviewer/presentation/presenter/PhotoDetailsPresenter.java // public class PhotoDetailsPresenter extends SimplePresenter { // // private final GetPhotoDetails mGetPhotoDetailsUseCase; // private final PhotoToPhotoModel mPhotoModelTransformer; // /** // * id used to retrieve photo details // */ // private int mPhotoId; // private PhotoDetailsView mViewDetailsView; // // @Inject // public PhotoDetailsPresenter(GetPhotoDetails getPhotoDetailsUseCase) { // mGetPhotoDetailsUseCase = getPhotoDetailsUseCase; // mPhotoModelTransformer = new PhotoToPhotoModel(); // } // // public void setView(@NonNull PhotoDetailsView view) { // mViewDetailsView = view; // } // // @Override // public void destroy() { // mGetPhotoDetailsUseCase.unsubscribe(); // } // // /** // * Initializes the presenter by start retrieving photo details. // */ // public void initialize(int photoId) { // mPhotoId = photoId; // loadPhotoDetails(); // } // // /** // * Loads photo details. // */ // private void loadPhotoDetails() { // hideViewRetry(); // showViewLoading(); // getPhotoDetails(); // } // // private void showViewLoading() { // mViewDetailsView.showLoading(); // } // // private void hideViewLoading() { // mViewDetailsView.hideLoading(); // } // // private void showViewRetry() { // mViewDetailsView.showRetry(); // } // // private void hideViewRetry() { // mViewDetailsView.hideRetry(); // } // // private void showErrorMessage() { // //TODO implement // String errorMessage = "Error happened"; // mViewDetailsView.showError(errorMessage); // } // // private void showPhotoDetailsInView(Photo photo) { // final PhotoModel photoModel = mPhotoModelTransformer.transform(photo); // mViewDetailsView.renderPhoto(photoModel); // } // // private void getPhotoDetails() { // mGetPhotoDetailsUseCase.setPhotoId(mPhotoId); // mGetPhotoDetailsUseCase.execute(new PhotoDetailsSubscriber()); // } // // private final class PhotoDetailsSubscriber extends SimpleSubscriber<Photo> { // // @Override // public void onCompleted() { // PhotoDetailsPresenter.this.hideViewLoading(); // } // // @Override // public void onError(Throwable e) { // PhotoDetailsPresenter.this.hideViewLoading(); // PhotoDetailsPresenter.this.showErrorMessage(); // PhotoDetailsPresenter.this.showViewRetry(); // } // // @Override // public void onNext(Photo photo) { // PhotoDetailsPresenter.this.showPhotoDetailsInView(photo); // } // } // } // // Path: app/src/main/java/com/photoviewer/presentation/view/PhotoDetailsView.java // public interface PhotoDetailsView extends LoadDataView { // /** // * Render a photo in the UI. // * // * @param photo The {@link PhotoModel} that will be shown. // */ // void renderPhoto(PhotoModel photo); // } // Path: app/src/main/java/com/photoviewer/presentation/view/activity/PhotoDetailsActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import com.photoviewer.R; import com.photoviewer.presentation.model.PhotoModel; import com.photoviewer.presentation.presenter.PhotoDetailsPresenter; import com.photoviewer.presentation.view.PhotoDetailsView; import com.squareup.picasso.Picasso; import javax.inject.Inject; } @Override public void hideRetry() { mRetryView.setVisibility(View.GONE); } @Override public void showError(String message) { showToastMessage(message); } private void showToastMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } /** * Loads all photos. */ private void loadPhotoDetails() { if (mPhotoDetailsPresenter != null) { mPhotoDetailsPresenter.initialize(mPhotoId); } } void onButtonRetryClick() { loadPhotoDetails(); } @Override
public void renderPhoto(PhotoModel photoModel) {
lifedemons/photoviewer
app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java
// Path: app/src/main/java/com/photoviewer/presentation/di/modules/AppModule.java // @Module(library = true, includes = { // ApiModule.class, DataModule.class, UseCasesModule.class, RxModule.class, // IntegrationTestsStaticModule.class // }) public class AppModule { // private Context mContext; // // public AppModule(Context context) { // mContext = context; // } // // @Provides Context providesApplicationContext() { // return mContext; // } // // @Provides @Singleton Resources getApplicationResources() { // return mContext.getResources(); // } // }
import android.app.Application; import com.photoviewer.presentation.di.modules.AppModule; import dagger.ObjectGraph;
package com.photoviewer.presentation; public class PhotoViewerApplication extends Application { @Override public void onCreate() { super.onCreate();
// Path: app/src/main/java/com/photoviewer/presentation/di/modules/AppModule.java // @Module(library = true, includes = { // ApiModule.class, DataModule.class, UseCasesModule.class, RxModule.class, // IntegrationTestsStaticModule.class // }) public class AppModule { // private Context mContext; // // public AppModule(Context context) { // mContext = context; // } // // @Provides Context providesApplicationContext() { // return mContext; // } // // @Provides @Singleton Resources getApplicationResources() { // return mContext.getResources(); // } // } // Path: app/src/main/java/com/photoviewer/presentation/PhotoViewerApplication.java import android.app.Application; import com.photoviewer.presentation.di.modules.AppModule; import dagger.ObjectGraph; package com.photoviewer.presentation; public class PhotoViewerApplication extends Application { @Override public void onCreate() { super.onCreate();
sObjectGraph = ObjectGraph.create(new AppModule(this));
lifedemons/photoviewer
app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/datastore/PreferencesPhotoStatisticsEntityStore.java // @Accessors(prefix = "m") // public class PreferencesPhotoStatisticsEntityStore { // // @Setter // private PreferencesDao<PhotoStatisticsEntity> mStatisticsDao; // // @Inject // public PreferencesPhotoStatisticsEntityStore(Context context) { // setStatisticsDao(new PreferencesDao<>(PhotoStatisticsEntity.class, context)); // } // // public Observable<PhotoStatisticsEntity> readStatistics() { // return Observable.create(new Observable.OnSubscribe<PhotoStatisticsEntity>() { // @Override // public void call(Subscriber<? super PhotoStatisticsEntity> subscriber) { // try { // PhotoStatisticsEntity statistics = mStatisticsDao.read(); // subscriber.onNext(statistics); // subscriber.onCompleted(); // } catch (Throwable e) { // subscriber.onError(e); // } // } // }); // } // // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return Observable.create(new Observable.OnSubscribe<PhotoStatisticsEntity>() { // @Override // public void call(Subscriber<? super PhotoStatisticsEntity> subscriber) { // try { // PhotoStatisticsEntity oldStatistics = mStatisticsDao.read(); // mStatisticsDao.save(photoStatisticsEntity); // subscriber.onNext(oldStatistics); // subscriber.onCompleted(); // } catch (Throwable e) { // subscriber.onError(e); // } // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // }
import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.datastore.PreferencesPhotoStatisticsEntityStore; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import javax.inject.Inject; import rx.Observable;
package com.photoviewer.data.repository; public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; @Override
// Path: app/src/main/java/com/photoviewer/data/entity/PhotoStatisticsEntity.java // @Accessors(prefix = "m") // @PreferenceFile(name = "photos_opening_statistics") // public class PhotoStatisticsEntity { // // @Setter // @Getter // @Preference(name = "last_opened_photo_id") // private int mLastOpenedPhotoId; // // @Setter // @Getter // @Preference(name = "opened_photos_count") // private int mOpenedPhotosCount; // } // // Path: app/src/main/java/com/photoviewer/data/repository/datastore/PreferencesPhotoStatisticsEntityStore.java // @Accessors(prefix = "m") // public class PreferencesPhotoStatisticsEntityStore { // // @Setter // private PreferencesDao<PhotoStatisticsEntity> mStatisticsDao; // // @Inject // public PreferencesPhotoStatisticsEntityStore(Context context) { // setStatisticsDao(new PreferencesDao<>(PhotoStatisticsEntity.class, context)); // } // // public Observable<PhotoStatisticsEntity> readStatistics() { // return Observable.create(new Observable.OnSubscribe<PhotoStatisticsEntity>() { // @Override // public void call(Subscriber<? super PhotoStatisticsEntity> subscriber) { // try { // PhotoStatisticsEntity statistics = mStatisticsDao.read(); // subscriber.onNext(statistics); // subscriber.onCompleted(); // } catch (Throwable e) { // subscriber.onError(e); // } // } // }); // } // // public Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity) { // return Observable.create(new Observable.OnSubscribe<PhotoStatisticsEntity>() { // @Override // public void call(Subscriber<? super PhotoStatisticsEntity> subscriber) { // try { // PhotoStatisticsEntity oldStatistics = mStatisticsDao.read(); // mStatisticsDao.save(photoStatisticsEntity); // subscriber.onNext(oldStatistics); // subscriber.onCompleted(); // } catch (Throwable e) { // subscriber.onError(e); // } // } // }); // } // } // // Path: app/src/main/java/com/photoviewer/domain/repository/PhotoStatisticsRepository.java // public interface PhotoStatisticsRepository { // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> readStatistics(); // // /** // * Get an {@link rx.Observable} which will emit {@link PhotoStatisticsEntity}. // */ // Observable<PhotoStatisticsEntity> updateStatistics(PhotoStatisticsEntity photoStatisticsEntity); // } // Path: app/src/main/java/com/photoviewer/data/repository/PhotoStatisticsEntityDataSource.java import com.photoviewer.data.entity.PhotoStatisticsEntity; import com.photoviewer.data.repository.datastore.PreferencesPhotoStatisticsEntityStore; import com.photoviewer.domain.repository.PhotoStatisticsRepository; import javax.inject.Inject; import rx.Observable; package com.photoviewer.data.repository; public class PhotoStatisticsEntityDataSource implements PhotoStatisticsRepository { @Inject PreferencesPhotoStatisticsEntityStore mStatisticsEntityStore; @Override
public Observable<PhotoStatisticsEntity> readStatistics() {
tarql/tarql
src/test/java/org/deri/tarql/StreamRDFDedupTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Triple triple(String tripleAsTurtle) { // Model m = ModelFactory.createDefaultModel(); // m.read(new StringReader(tripleAsTurtle), "urn:x-base:", "TURTLE"); // return m.listStatements().next().asTriple(); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Triple> triples(String... triples) { // List<Triple> results = new ArrayList<>(); // for (String triple: triples) { // results.add(triple(triple)); // } // return results; // }
import static org.deri.tarql.Helpers.triple; import static org.deri.tarql.Helpers.triples; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.sparql.core.Quad; import org.junit.Before; import org.junit.Test;
package org.deri.tarql; public class StreamRDFDedupTest { List<Object> received; @Before public void setUp() throws Exception { received = new ArrayList<Object>(); } @Test public void shouldPassThroughTriples() { StreamRDF dedup = new StreamRDFDedup(new MockStreamRDF()); dedup.start();
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Triple triple(String tripleAsTurtle) { // Model m = ModelFactory.createDefaultModel(); // m.read(new StringReader(tripleAsTurtle), "urn:x-base:", "TURTLE"); // return m.listStatements().next().asTriple(); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Triple> triples(String... triples) { // List<Triple> results = new ArrayList<>(); // for (String triple: triples) { // results.add(triple(triple)); // } // return results; // } // Path: src/test/java/org/deri/tarql/StreamRDFDedupTest.java import static org.deri.tarql.Helpers.triple; import static org.deri.tarql.Helpers.triples; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.sparql.core.Quad; import org.junit.Before; import org.junit.Test; package org.deri.tarql; public class StreamRDFDedupTest { List<Object> received; @Before public void setUp() throws Exception { received = new ArrayList<Object>(); } @Test public void shouldPassThroughTriples() { StreamRDF dedup = new StreamRDFDedup(new MockStreamRDF()); dedup.start();
dedup.triple(triple("<a> <a> <a>"));
tarql/tarql
src/test/java/org/deri/tarql/StreamRDFDedupTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Triple triple(String tripleAsTurtle) { // Model m = ModelFactory.createDefaultModel(); // m.read(new StringReader(tripleAsTurtle), "urn:x-base:", "TURTLE"); // return m.listStatements().next().asTriple(); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Triple> triples(String... triples) { // List<Triple> results = new ArrayList<>(); // for (String triple: triples) { // results.add(triple(triple)); // } // return results; // }
import static org.deri.tarql.Helpers.triple; import static org.deri.tarql.Helpers.triples; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.sparql.core.Quad; import org.junit.Before; import org.junit.Test;
package org.deri.tarql; public class StreamRDFDedupTest { List<Object> received; @Before public void setUp() throws Exception { received = new ArrayList<Object>(); } @Test public void shouldPassThroughTriples() { StreamRDF dedup = new StreamRDFDedup(new MockStreamRDF()); dedup.start(); dedup.triple(triple("<a> <a> <a>")); dedup.triple(triple("<b> <b> <b>")); dedup.triple(triple("<c> <c> <c>")); dedup.finish();
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Triple triple(String tripleAsTurtle) { // Model m = ModelFactory.createDefaultModel(); // m.read(new StringReader(tripleAsTurtle), "urn:x-base:", "TURTLE"); // return m.listStatements().next().asTriple(); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Triple> triples(String... triples) { // List<Triple> results = new ArrayList<>(); // for (String triple: triples) { // results.add(triple(triple)); // } // return results; // } // Path: src/test/java/org/deri/tarql/StreamRDFDedupTest.java import static org.deri.tarql.Helpers.triple; import static org.deri.tarql.Helpers.triples; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.sparql.core.Quad; import org.junit.Before; import org.junit.Test; package org.deri.tarql; public class StreamRDFDedupTest { List<Object> received; @Before public void setUp() throws Exception { received = new ArrayList<Object>(); } @Test public void shouldPassThroughTriples() { StreamRDF dedup = new StreamRDFDedup(new MockStreamRDF()); dedup.start(); dedup.triple(triple("<a> <a> <a>")); dedup.triple(triple("<b> <b> <b>")); dedup.triple(triple("<c> <c> <c>")); dedup.finish();
assertEquals(triples("<a> <a> <a>", "<b> <b> <b>", "<c> <c> <c>"), received);
tarql/tarql
src/test/java/org/deri/tarql/TarqlTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.JenaException; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Before; import org.junit.Test;
} ResultSet rs = ex.execSelect(); int counter = 0; while (rs.hasNext()) { if (counter >= bindings.length) { fail("Too many bindings in result; expected " + bindings.length); } assertEquals(bindings[counter], rs.nextBinding()); counter += 1; } assertEquals(bindings.length, counter); } private void assertConstruct(TarqlQuery tq, String expectedTTL) throws IOException { Model expected = ModelFactory.createDefaultModel().read(new StringReader(expectedTTL), null, "TURTLE"); TarqlQueryExecution ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options); Model actual = ModelFactory.createDefaultModel(); ex.exec(actual); if (!actual.isIsomorphicWith(expected)) { StringWriter out = new StringWriter(); actual.write(out, "TURTLE"); fail("Actual not isomorphic to input. Actual was:\n" + out.toString()); } } @Test public void testSimpleSelect() throws IOException { csv = "Alice,Smith\nBob,Cook"; String query = "SELECT * {}"; TarqlQuery tq = new TarqlParser(new StringReader(query), null).getResult();
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/TarqlTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.JenaException; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Before; import org.junit.Test; } ResultSet rs = ex.execSelect(); int counter = 0; while (rs.hasNext()) { if (counter >= bindings.length) { fail("Too many bindings in result; expected " + bindings.length); } assertEquals(bindings[counter], rs.nextBinding()); counter += 1; } assertEquals(bindings.length, counter); } private void assertConstruct(TarqlQuery tq, String expectedTTL) throws IOException { Model expected = ModelFactory.createDefaultModel().read(new StringReader(expectedTTL), null, "TURTLE"); TarqlQueryExecution ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options); Model actual = ModelFactory.createDefaultModel(); ex.exec(actual); if (!actual.isIsomorphicWith(expected)) { StringWriter out = new StringWriter(); actual.write(out, "TURTLE"); fail("Actual not isomorphic to input. Actual was:\n" + out.toString()); } } @Test public void testSimpleSelect() throws IOException { csv = "Alice,Smith\nBob,Cook"; String query = "SELECT * {}"; TarqlQuery tq = new TarqlParser(new StringReader(query), null).getResult();
List<Var> vars = vars("a", "b");
tarql/tarql
src/test/java/org/deri/tarql/TarqlTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.JenaException; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Before; import org.junit.Test;
ResultSet rs = ex.execSelect(); int counter = 0; while (rs.hasNext()) { if (counter >= bindings.length) { fail("Too many bindings in result; expected " + bindings.length); } assertEquals(bindings[counter], rs.nextBinding()); counter += 1; } assertEquals(bindings.length, counter); } private void assertConstruct(TarqlQuery tq, String expectedTTL) throws IOException { Model expected = ModelFactory.createDefaultModel().read(new StringReader(expectedTTL), null, "TURTLE"); TarqlQueryExecution ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options); Model actual = ModelFactory.createDefaultModel(); ex.exec(actual); if (!actual.isIsomorphicWith(expected)) { StringWriter out = new StringWriter(); actual.write(out, "TURTLE"); fail("Actual not isomorphic to input. Actual was:\n" + out.toString()); } } @Test public void testSimpleSelect() throws IOException { csv = "Alice,Smith\nBob,Cook"; String query = "SELECT * {}"; TarqlQuery tq = new TarqlParser(new StringReader(query), null).getResult(); List<Var> vars = vars("a", "b");
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/TarqlTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.JenaException; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Before; import org.junit.Test; ResultSet rs = ex.execSelect(); int counter = 0; while (rs.hasNext()) { if (counter >= bindings.length) { fail("Too many bindings in result; expected " + bindings.length); } assertEquals(bindings[counter], rs.nextBinding()); counter += 1; } assertEquals(bindings.length, counter); } private void assertConstruct(TarqlQuery tq, String expectedTTL) throws IOException { Model expected = ModelFactory.createDefaultModel().read(new StringReader(expectedTTL), null, "TURTLE"); TarqlQueryExecution ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options); Model actual = ModelFactory.createDefaultModel(); ex.exec(actual); if (!actual.isIsomorphicWith(expected)) { StringWriter out = new StringWriter(); actual.write(out, "TURTLE"); fail("Actual not isomorphic to input. Actual was:\n" + out.toString()); } } @Test public void testSimpleSelect() throws IOException { csv = "Alice,Smith\nBob,Cook"; String query = "SELECT * {}"; TarqlQuery tq = new TarqlParser(new StringReader(query), null).getResult(); List<Var> vars = vars("a", "b");
assertSelect(tq, binding(vars, "\"Alice\"", "\"Smith\""), binding(vars, "\"Bob\"", "\"Cook\""));
tarql/tarql
src/main/java/org/deri/tarql/TarqlQuery.java
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // // Path: src/main/java/org/deri/tarql/functions/ExpandPrefixedNameFunction.java // public class ExpandPrefixedNameFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefixedName"; // public static String Name = "tarql:expandPrefixedName"; // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixedNameFunction() { // super(); // } // // public NodeValue exec(NodeValue name, Context context) { // if (name == null) return null; // if (!name.isString()) throw new ExprEvalException("Not a string: " + name); // PrefixMapping prefixes = context.get(ExpandPrefixFunction.PREFIX_MAPPING); // if (prefixes == null) throw new ExprEvalException("No prefix mapping registered"); // String pname = name.asString(); // int idx = pname.indexOf(':'); // if (idx == -1) throw new ExprEvalException("Not a prefixed name: " + name); // String prefix = pname.substring(0, idx); // String iri = prefixes.getNsPrefixURI(prefix); // if (iri == null) throw new ExprEvalException("Prefix not defined: " + prefix); // return NodeValue.makeNode(NodeFactory.createURI(iri + pname.substring(idx + 1))); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // }
import java.util.ArrayList; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.sparql.core.Prologue; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.function.FunctionRegistry; import org.deri.tarql.functions.ExpandPrefixFunction; import org.deri.tarql.functions.ExpandPrefixedNameFunction;
package org.deri.tarql; /** * A Tarql mapping. Conceptually, this is one or more SPARQL queries * with a shared prologue (prefixes and base declarations). */ public class TarqlQuery { static { registerFunctions(); } public static void registerFunctions() { if (registered) return; registered = true;
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // // Path: src/main/java/org/deri/tarql/functions/ExpandPrefixedNameFunction.java // public class ExpandPrefixedNameFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefixedName"; // public static String Name = "tarql:expandPrefixedName"; // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixedNameFunction() { // super(); // } // // public NodeValue exec(NodeValue name, Context context) { // if (name == null) return null; // if (!name.isString()) throw new ExprEvalException("Not a string: " + name); // PrefixMapping prefixes = context.get(ExpandPrefixFunction.PREFIX_MAPPING); // if (prefixes == null) throw new ExprEvalException("No prefix mapping registered"); // String pname = name.asString(); // int idx = pname.indexOf(':'); // if (idx == -1) throw new ExprEvalException("Not a prefixed name: " + name); // String prefix = pname.substring(0, idx); // String iri = prefixes.getNsPrefixURI(prefix); // if (iri == null) throw new ExprEvalException("Prefix not defined: " + prefix); // return NodeValue.makeNode(NodeFactory.createURI(iri + pname.substring(idx + 1))); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // Path: src/main/java/org/deri/tarql/TarqlQuery.java import java.util.ArrayList; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.sparql.core.Prologue; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.function.FunctionRegistry; import org.deri.tarql.functions.ExpandPrefixFunction; import org.deri.tarql.functions.ExpandPrefixedNameFunction; package org.deri.tarql; /** * A Tarql mapping. Conceptually, this is one or more SPARQL queries * with a shared prologue (prefixes and base declarations). */ public class TarqlQuery { static { registerFunctions(); } public static void registerFunctions() { if (registered) return; registered = true;
FunctionRegistry.get().put(ExpandPrefixFunction.IRI, ExpandPrefixFunction.class);
tarql/tarql
src/main/java/org/deri/tarql/TarqlQuery.java
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // // Path: src/main/java/org/deri/tarql/functions/ExpandPrefixedNameFunction.java // public class ExpandPrefixedNameFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefixedName"; // public static String Name = "tarql:expandPrefixedName"; // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixedNameFunction() { // super(); // } // // public NodeValue exec(NodeValue name, Context context) { // if (name == null) return null; // if (!name.isString()) throw new ExprEvalException("Not a string: " + name); // PrefixMapping prefixes = context.get(ExpandPrefixFunction.PREFIX_MAPPING); // if (prefixes == null) throw new ExprEvalException("No prefix mapping registered"); // String pname = name.asString(); // int idx = pname.indexOf(':'); // if (idx == -1) throw new ExprEvalException("Not a prefixed name: " + name); // String prefix = pname.substring(0, idx); // String iri = prefixes.getNsPrefixURI(prefix); // if (iri == null) throw new ExprEvalException("Prefix not defined: " + prefix); // return NodeValue.makeNode(NodeFactory.createURI(iri + pname.substring(idx + 1))); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // }
import java.util.ArrayList; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.sparql.core.Prologue; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.function.FunctionRegistry; import org.deri.tarql.functions.ExpandPrefixFunction; import org.deri.tarql.functions.ExpandPrefixedNameFunction;
package org.deri.tarql; /** * A Tarql mapping. Conceptually, this is one or more SPARQL queries * with a shared prologue (prefixes and base declarations). */ public class TarqlQuery { static { registerFunctions(); } public static void registerFunctions() { if (registered) return; registered = true; FunctionRegistry.get().put(ExpandPrefixFunction.IRI, ExpandPrefixFunction.class);
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // // Path: src/main/java/org/deri/tarql/functions/ExpandPrefixedNameFunction.java // public class ExpandPrefixedNameFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefixedName"; // public static String Name = "tarql:expandPrefixedName"; // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixedNameFunction() { // super(); // } // // public NodeValue exec(NodeValue name, Context context) { // if (name == null) return null; // if (!name.isString()) throw new ExprEvalException("Not a string: " + name); // PrefixMapping prefixes = context.get(ExpandPrefixFunction.PREFIX_MAPPING); // if (prefixes == null) throw new ExprEvalException("No prefix mapping registered"); // String pname = name.asString(); // int idx = pname.indexOf(':'); // if (idx == -1) throw new ExprEvalException("Not a prefixed name: " + name); // String prefix = pname.substring(0, idx); // String iri = prefixes.getNsPrefixURI(prefix); // if (iri == null) throw new ExprEvalException("Prefix not defined: " + prefix); // return NodeValue.makeNode(NodeFactory.createURI(iri + pname.substring(idx + 1))); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // Path: src/main/java/org/deri/tarql/TarqlQuery.java import java.util.ArrayList; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.sparql.core.Prologue; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.function.FunctionRegistry; import org.deri.tarql.functions.ExpandPrefixFunction; import org.deri.tarql.functions.ExpandPrefixedNameFunction; package org.deri.tarql; /** * A Tarql mapping. Conceptually, this is one or more SPARQL queries * with a shared prologue (prefixes and base declarations). */ public class TarqlQuery { static { registerFunctions(); } public static void registerFunctions() { if (registered) return; registered = true; FunctionRegistry.get().put(ExpandPrefixFunction.IRI, ExpandPrefixFunction.class);
FunctionRegistry.get().put(ExpandPrefixedNameFunction.IRI, ExpandPrefixedNameFunction.class);
tarql/tarql
src/test/java/org/deri/tarql/CSVParserTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test;
package org.deri.tarql; public class CSVParserTest { @Test public void testColumnName() { assertEquals("a", CSVParser.getColumnName(0)); assertEquals("b", CSVParser.getColumnName(1)); assertEquals("c", CSVParser.getColumnName(2)); assertEquals("z", CSVParser.getColumnName(25)); assertEquals("aa", CSVParser.getColumnName(26)); assertEquals("ab", CSVParser.getColumnName(27)); } @Test public void testCountVars() throws IOException { String csv = "1\n1,1,1\n1,1"; assertEquals(3, countRows(csv, false)); } @Test public void testHeading() throws IOException { String csv = "1,2,3,4,5";
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/CSVParserTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test; package org.deri.tarql; public class CSVParserTest { @Test public void testColumnName() { assertEquals("a", CSVParser.getColumnName(0)); assertEquals("b", CSVParser.getColumnName(1)); assertEquals("c", CSVParser.getColumnName(2)); assertEquals("z", CSVParser.getColumnName(25)); assertEquals("aa", CSVParser.getColumnName(26)); assertEquals("ab", CSVParser.getColumnName(27)); } @Test public void testCountVars() throws IOException { String csv = "1\n1,1,1\n1,1"; assertEquals(3, countRows(csv, false)); } @Test public void testHeading() throws IOException { String csv = "1,2,3,4,5";
assertEquals(vars("a", "b", "c", "d", "e"), getNonPseudoVars(csv, false));
tarql/tarql
src/test/java/org/deri/tarql/CSVParserTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test;
package org.deri.tarql; public class CSVParserTest { @Test public void testColumnName() { assertEquals("a", CSVParser.getColumnName(0)); assertEquals("b", CSVParser.getColumnName(1)); assertEquals("c", CSVParser.getColumnName(2)); assertEquals("z", CSVParser.getColumnName(25)); assertEquals("aa", CSVParser.getColumnName(26)); assertEquals("ab", CSVParser.getColumnName(27)); } @Test public void testCountVars() throws IOException { String csv = "1\n1,1,1\n1,1"; assertEquals(3, countRows(csv, false)); } @Test public void testHeading() throws IOException { String csv = "1,2,3,4,5"; assertEquals(vars("a", "b", "c", "d", "e"), getNonPseudoVars(csv, false)); } @Test public void testUnbound() throws IOException { String csv = "1\n1,1";
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/CSVParserTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test; package org.deri.tarql; public class CSVParserTest { @Test public void testColumnName() { assertEquals("a", CSVParser.getColumnName(0)); assertEquals("b", CSVParser.getColumnName(1)); assertEquals("c", CSVParser.getColumnName(2)); assertEquals("z", CSVParser.getColumnName(25)); assertEquals("aa", CSVParser.getColumnName(26)); assertEquals("ab", CSVParser.getColumnName(27)); } @Test public void testCountVars() throws IOException { String csv = "1\n1,1,1\n1,1"; assertEquals(3, countRows(csv, false)); } @Test public void testHeading() throws IOException { String csv = "1,2,3,4,5"; assertEquals(vars("a", "b", "c", "d", "e"), getNonPseudoVars(csv, false)); } @Test public void testUnbound() throws IOException { String csv = "1\n1,1";
Binding binding = readCSV(csv, false).next();
tarql/tarql
src/test/java/org/deri/tarql/CSVParserTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test;
public void testHeading() throws IOException { String csv = "1,2,3,4,5"; assertEquals(vars("a", "b", "c", "d", "e"), getNonPseudoVars(csv, false)); } @Test public void testUnbound() throws IOException { String csv = "1\n1,1"; Binding binding = readCSV(csv, false).next(); assertEquals(null, binding.get(Var.alloc("b"))); } @Test public void testNoEmptyStrings() throws IOException { String csv = ",1"; assertEquals(null, readCSV(csv, false).next().get(Var.alloc("a"))); } @Test public void testSkipEmptyLines() throws IOException { String csv = "\n,,,,\n1"; assertEquals(1, countRows(csv, false)); } @Test public void testWithHeaders() throws IOException { String csv = "X,Y\n1,2"; assertEquals(1, countRows(csv, true)); assertEquals(vars("X", "Y"), getNonPseudoVars(csv, true));
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding removePseudoVars(Binding binding) { // BindingHashMap result = new BindingHashMap(); // Iterator<Var> it = binding.vars(); // while (it.hasNext()) { // Var var = it.next(); // if (var.equals(TarqlQuery.ROWNUM)) continue; // result.add(var, binding.get(var)); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/CSVParserTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.removePseudoVars; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test; public void testHeading() throws IOException { String csv = "1,2,3,4,5"; assertEquals(vars("a", "b", "c", "d", "e"), getNonPseudoVars(csv, false)); } @Test public void testUnbound() throws IOException { String csv = "1\n1,1"; Binding binding = readCSV(csv, false).next(); assertEquals(null, binding.get(Var.alloc("b"))); } @Test public void testNoEmptyStrings() throws IOException { String csv = ",1"; assertEquals(null, readCSV(csv, false).next().get(Var.alloc("a"))); } @Test public void testSkipEmptyLines() throws IOException { String csv = "\n,,,,\n1"; assertEquals(1, countRows(csv, false)); } @Test public void testWithHeaders() throws IOException { String csv = "X,Y\n1,2"; assertEquals(1, countRows(csv, true)); assertEquals(vars("X", "Y"), getNonPseudoVars(csv, true));
assertEquals(binding(vars("X", "Y"), "\"1\"", "\"2\""), removePseudoVars(readCSV(csv,true).next()));
tarql/tarql
src/main/java/org/deri/tarql/TarqlQueryExecution.java
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // }
import java.io.IOException; import java.util.Iterator; import org.apache.jena.graph.Triple; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.impl.PrefixMappingImpl; import org.apache.jena.sparql.algebra.Table; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.syntax.Element; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.apache.jena.util.iterator.ExtendedIterator; import org.apache.jena.util.iterator.NullIterator; import org.deri.tarql.functions.ExpandPrefixFunction;
} else { groupElement.addElement(query.getQueryPattern()); } query.setQueryPattern(groupElement); // For SELECT * queries, we don't want to include pseudo // columns such as ?ROWNUM that may exist in the table. // That's why we skipped ?ROWNUM further up. if (query.isSelectType() && query.isQueryResultStar()) { // Force expansion of "SELECT *" to actual projection list query.setResultVars(); // Tell ARQ that it actually needs to pay attention to // the projection list query.setQueryResultStar(false); // And now we can add ?ROWNUM to the table, as the "*" // has already been expanded. tableElement.add(TarqlQuery.ROWNUM); } // Data can only be added to table after we've finished the // ?ROWNUM shenangians /*for (Binding binding: table.getRows()) { tableElement.add(binding); }*/ } private QueryExecution createQueryExecution(Query query, Model model) { QueryExecution result = QueryExecutionFactory.create(query, model); PrefixMappingImpl prefixes = new PrefixMappingImpl(); prefixes.setNsPrefixes(tq.getPrologue().getPrefixMapping()); prefixes.setNsPrefix("tarql", tarql.NS);
// Path: src/main/java/org/deri/tarql/functions/ExpandPrefixFunction.java // public class ExpandPrefixFunction implements Function { // // public static String IRI = tarql.NS + "expandPrefix"; // public static String NAME = "tarql:expandPrefix"; // // public static final Symbol PREFIX_MAPPING = Symbol.create("prefixMapping"); // // static { // TarqlQuery.registerFunctions(); // } // // public ExpandPrefixFunction() { // super(); // } // // public NodeValue exec(NodeValue prefix, Context context) { // if (prefix == null) { // return null; // } // if (!prefix.isString()) { // throw new ExprEvalException(NAME + ": not a string: " + prefix); // } // PrefixMapping prefixes = context.get(PREFIX_MAPPING); // if (prefixes == null) { // throw new ExprEvalException(NAME + ": no prefix mapping registered"); // } // String iri = prefixes.getNsPrefixURI(prefix.asString()); // if (iri == null) { // throw new ExprEvalException(NAME + ": prefix not defined: " + prefix); // } // return NodeValue.makeString(iri); // } // // @Override // public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { // if (args == null) { // throw new ARQInternalErrorException("ExpandPrefixFunction: Null args list"); // } // if (args.size() != 1) { // throw new ExprEvalException("ExpandPrefixFunction: Wrong number of arguments: Wanted 1, got " + args.size()); // } // return exec(args.get(0).eval(binding, env), env.getContext()); // } // // @Override // public void build(String uri, ExprList args) { // if (args.size() != 1) { // throw new QueryBuildException("Function '" + Lib.className(this) + "' takes one argument"); // } // } // } // Path: src/main/java/org/deri/tarql/TarqlQueryExecution.java import java.io.IOException; import java.util.Iterator; import org.apache.jena.graph.Triple; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.shared.impl.PrefixMappingImpl; import org.apache.jena.sparql.algebra.Table; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.syntax.Element; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.apache.jena.util.iterator.ExtendedIterator; import org.apache.jena.util.iterator.NullIterator; import org.deri.tarql.functions.ExpandPrefixFunction; } else { groupElement.addElement(query.getQueryPattern()); } query.setQueryPattern(groupElement); // For SELECT * queries, we don't want to include pseudo // columns such as ?ROWNUM that may exist in the table. // That's why we skipped ?ROWNUM further up. if (query.isSelectType() && query.isQueryResultStar()) { // Force expansion of "SELECT *" to actual projection list query.setResultVars(); // Tell ARQ that it actually needs to pay attention to // the projection list query.setQueryResultStar(false); // And now we can add ?ROWNUM to the table, as the "*" // has already been expanded. tableElement.add(TarqlQuery.ROWNUM); } // Data can only be added to table after we've finished the // ?ROWNUM shenangians /*for (Binding binding: table.getRows()) { tableElement.add(binding); }*/ } private QueryExecution createQueryExecution(Query query, Model model) { QueryExecution result = QueryExecutionFactory.create(query, model); PrefixMappingImpl prefixes = new PrefixMappingImpl(); prefixes.setNsPrefixes(tq.getPrologue().getPrefixMapping()); prefixes.setNsPrefix("tarql", tarql.NS);
result.getContext().set(ExpandPrefixFunction.PREFIX_MAPPING, prefixes);
tarql/tarql
src/test/java/org/deri/tarql/CSVTableTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.QueryIterator; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test;
package org.deri.tarql; public class CSVTableTest { private void assertContents(Iterator<Binding> it, Binding... bindings) { int counter = 0; while (it.hasNext()) { assertEquals(bindings[counter], it.next()); counter += 1; } assertEquals(bindings.length, counter); } @Test public void testEmpty() throws IOException { CSVTable table = new CSVTable(InputStreamSource.fromString("")); assertTrue(table.isEmpty()); assertEquals(0, table.size());
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/CSVTableTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.QueryIterator; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test; package org.deri.tarql; public class CSVTableTest { private void assertContents(Iterator<Binding> it, Binding... bindings) { int counter = 0; while (it.hasNext()) { assertEquals(bindings[counter], it.next()); counter += 1; } assertEquals(bindings.length, counter); } @Test public void testEmpty() throws IOException { CSVTable table = new CSVTable(InputStreamSource.fromString("")); assertTrue(table.isEmpty()); assertEquals(0, table.size());
assertEquals(vars("ROWNUM"), table.getVars());
tarql/tarql
src/test/java/org/deri/tarql/CSVTableTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.QueryIterator; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test;
package org.deri.tarql; public class CSVTableTest { private void assertContents(Iterator<Binding> it, Binding... bindings) { int counter = 0; while (it.hasNext()) { assertEquals(bindings[counter], it.next()); counter += 1; } assertEquals(bindings.length, counter); } @Test public void testEmpty() throws IOException { CSVTable table = new CSVTable(InputStreamSource.fromString("")); assertTrue(table.isEmpty()); assertEquals(0, table.size()); assertEquals(vars("ROWNUM"), table.getVars()); assertFalse(table.rows().hasNext()); assertFalse(table.iterator(null).hasNext()); } @Test public void testSimpleTable() throws IOException { CSVOptions options = new CSVOptions(); options.setColumnNamesInFirstRow(false); CSVTable table = new CSVTable(InputStreamSource.fromString("Alice,Smith\nBob,Cook"), options); assertFalse(table.isEmpty()); assertEquals(2, table.size()); List<Var> vars = vars("a", "b", "ROWNUM"); assertEquals(vars, table.getVars());
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/CSVTableTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.vars; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.QueryIterator; import org.apache.jena.sparql.engine.binding.Binding; import org.junit.Test; package org.deri.tarql; public class CSVTableTest { private void assertContents(Iterator<Binding> it, Binding... bindings) { int counter = 0; while (it.hasNext()) { assertEquals(bindings[counter], it.next()); counter += 1; } assertEquals(bindings.length, counter); } @Test public void testEmpty() throws IOException { CSVTable table = new CSVTable(InputStreamSource.fromString("")); assertTrue(table.isEmpty()); assertEquals(0, table.size()); assertEquals(vars("ROWNUM"), table.getVars()); assertFalse(table.rows().hasNext()); assertFalse(table.iterator(null).hasNext()); } @Test public void testSimpleTable() throws IOException { CSVOptions options = new CSVOptions(); options.setColumnNamesInFirstRow(false); CSVTable table = new CSVTable(InputStreamSource.fromString("Alice,Smith\nBob,Cook"), options); assertFalse(table.isEmpty()); assertEquals(2, table.size()); List<Var> vars = vars("a", "b", "ROWNUM"); assertEquals(vars, table.getVars());
Binding[] bindings = {binding(vars, "\"Alice\"", "\"Smith\"", "1"), binding(vars, "\"Bob\"", "\"Cook\"", "2")};
tarql/tarql
src/test/java/org/deri/tarql/ARQTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase;
package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext());
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/ARQTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase; package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext());
assertEquals(binding(vars("a"), "1"), rs.nextBinding());
tarql/tarql
src/test/java/org/deri/tarql/ARQTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase;
package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext());
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/ARQTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase; package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext());
assertEquals(binding(vars("a"), "1"), rs.nextBinding());
tarql/tarql
src/test/java/org/deri/tarql/ARQTest.java
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // }
import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase;
package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext()); assertEquals(binding(vars("a"), "1"), rs.nextBinding()); assertFalse(rs.hasNext()); } @Test public void testQuerySetValuesDataBlock() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}");
// Path: src/test/java/org/deri/tarql/Helpers.java // public static Binding binding(List<Var> header, String... values) { // if (header.size() != values.length) { // throw new IllegalArgumentException( // "header and values must have same length: " + // header + ", " + Arrays.toString(values)); // } // BindingHashMap result = new BindingHashMap(); // for (int i = 0; i < header.size(); i++) { // result.add(header.get(i), NodeFactoryExtra.parseNode(values[i])); // } // return result; // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Binding> bindings(Binding... bindings) { // return Arrays.asList(bindings); // } // // Path: src/test/java/org/deri/tarql/Helpers.java // public static List<Var> vars(String... names) { // List<Var> result = new ArrayList<Var>(names.length); // for (String name: names) { // result.add(Var.alloc(name)); // } // return result; // } // Path: src/test/java/org/deri/tarql/ARQTest.java import static org.deri.tarql.Helpers.binding; import static org.deri.tarql.Helpers.bindings; import static org.deri.tarql.Helpers.vars; import java.util.Arrays; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.syntax.ElementData; import org.apache.jena.sparql.syntax.ElementGroup; import org.junit.Test; import junit.framework.TestCase; package org.deri.tarql; public class ARQTest extends TestCase { @Test public void testSPARQLFilterIsAppliedToValues() { Query q = QueryFactory.create( "SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }"); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertTrue(rs.hasNext()); assertEquals(binding(vars("a"), "1"), rs.nextBinding()); assertFalse(rs.hasNext()); } @Test public void testQuerySetValuesDataBlock() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}");
q.setValuesDataBlock(header, bindings(b1, b2));
be-hase/relumin
src/main/java/com/behase/relumin/exception/ApiException.java
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.model.ErrorResponse; import lombok.Getter; import lombok.Setter; import org.springframework.http.HttpStatus;
package com.behase.relumin.exception; public class ApiException extends RuntimeException { private static final long serialVersionUID = 3285456520279227122L; @Getter @Setter
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/main/java/com/behase/relumin/exception/ApiException.java import com.behase.relumin.model.ErrorResponse; import lombok.Getter; import lombok.Setter; import org.springframework.http.HttpStatus; package com.behase.relumin.exception; public class ApiException extends RuntimeException { private static final long serialVersionUID = 3285456520279227122L; @Getter @Setter
private ErrorResponse errorResponse;
be-hase/relumin
src/test/java/com/behase/relumin/controller/UserApiControllerTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/UserApiControllerTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock
private UserService userService;
be-hase/relumin
src/test/java/com/behase/relumin/controller/UserApiControllerTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/UserApiControllerTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock
private LoggingOperationService loggingOperationService;
be-hase/relumin
src/test/java/com/behase/relumin/controller/UserApiControllerTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock private LoggingOperationService loggingOperationService; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers();
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/UserApiControllerTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock private LoggingOperationService loggingOperationService; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers();
List<LoginUser> result = controller.users();
be-hase/relumin
src/test/java/com/behase/relumin/controller/UserApiControllerTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock private LoggingOperationService loggingOperationService; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers(); List<LoginUser> result = controller.users(); log.info("result={}", result); assertThat(result, is(empty())); } @Test public void add() throws Exception {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/UserApiControllerTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @Slf4j @RunWith(MockitoJUnitRunner.class) public class UserApiControllerTest { @InjectMocks @Spy private UserApiController controller = new UserApiController(); @Mock private UserService userService; @Mock private LoggingOperationService loggingOperationService; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers(); List<LoginUser> result = controller.users(); log.info("result={}", result); assertThat(result, is(empty())); } @Test public void add() throws Exception {
doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString());
be-hase/relumin
src/test/java/com/behase/relumin/controller/UserApiControllerTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
@Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers(); List<LoginUser> result = controller.users(); log.info("result={}", result); assertThat(result, is(empty())); } @Test public void add() throws Exception { doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString()); LoginUser result = controller.add(null, "", "", "", ""); log.info("result={}", result); assertThat(result.getUsername(), is("username")); } @Test public void update() throws Exception { doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString()); LoginUser result = controller.update(null, "", "", ""); log.info("result={}", result); assertThat(result.getUsername(), is("username")); } @Test public void updateMe_authentication_is_null_throw_exception() throws Exception {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/UserApiControllerTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @Test public void users() throws Exception { doReturn(Lists.newArrayList()).when(userService).getUsers(); List<LoginUser> result = controller.users(); log.info("result={}", result); assertThat(result, is(empty())); } @Test public void add() throws Exception { doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString()); LoginUser result = controller.add(null, "", "", "", ""); log.info("result={}", result); assertThat(result.getUsername(), is("username")); } @Test public void update() throws Exception { doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString()); LoginUser result = controller.update(null, "", "", ""); log.info("result={}", result); assertThat(result.getUsername(), is("username")); } @Test public void updateMe_authentication_is_null_throw_exception() throws Exception {
expectedEx.expect(InvalidParameterException.class);
be-hase/relumin
src/test/java/com/behase/relumin/support/TribClusterNodeTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*;
package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class TribClusterNodeTest { @Spy private TribClusterNode tested = new TribClusterNode("localhost:10000"); @Mock private Jedis jedis; @Mock private JedisSupport jedisSupport; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { doReturn(jedisSupport).when(tested).createJedisSupport(); doReturn(jedis).when(jedisSupport).getJedisByHostAndPort(anyString()); } private void initConnect() { tested.connect(); } @Test public void constructor_invalid_host_and_port() {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/test/java/com/behase/relumin/support/TribClusterNodeTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class TribClusterNodeTest { @Spy private TribClusterNode tested = new TribClusterNode("localhost:10000"); @Mock private Jedis jedis; @Mock private JedisSupport jedisSupport; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { doReturn(jedisSupport).when(tested).createJedisSupport(); doReturn(jedis).when(jedisSupport).getJedisByHostAndPort(anyString()); } private void initConnect() { tested.connect(); } @Test public void constructor_invalid_host_and_port() {
expectedEx.expect(InvalidParameterException.class);
be-hase/relumin
src/test/java/com/behase/relumin/support/TribClusterNodeTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*;
} @Test public void assertEmpty_cluster_known_nodes_is_not_1_then_throw_exception() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage(containsString("is not empty. Either the node already knows other nodes")); // given initConnect(); doReturn(Maps.newHashMap()).when(jedisSupport).parseInfoResult(anyString()); doReturn(ImmutableMap.of("cluster_known_nodes", "0")).when(jedisSupport).parseClusterInfoResult(anyString()); // when tested.assertEmpty(); } @Test public void assertEmpty() { // given initConnect(); doReturn(Maps.newHashMap()).when(jedisSupport).parseInfoResult(anyString()); doReturn(ImmutableMap.of("cluster_known_nodes", "1")).when(jedisSupport).parseClusterInfoResult(anyString()); // when tested.assertEmpty(); } @Test public void loadInfo_getFriends_true() { // given
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/test/java/com/behase/relumin/support/TribClusterNodeTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; } @Test public void assertEmpty_cluster_known_nodes_is_not_1_then_throw_exception() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage(containsString("is not empty. Either the node already knows other nodes")); // given initConnect(); doReturn(Maps.newHashMap()).when(jedisSupport).parseInfoResult(anyString()); doReturn(ImmutableMap.of("cluster_known_nodes", "0")).when(jedisSupport).parseClusterInfoResult(anyString()); // when tested.assertEmpty(); } @Test public void assertEmpty() { // given initConnect(); doReturn(Maps.newHashMap()).when(jedisSupport).parseInfoResult(anyString()); doReturn(ImmutableMap.of("cluster_known_nodes", "1")).when(jedisSupport).parseClusterInfoResult(anyString()); // when tested.assertEmpty(); } @Test public void loadInfo_getFriends_true() { // given
List<ClusterNode> nodes = Lists.newArrayList(
be-hase/relumin
src/main/java/com/behase/relumin/config/ReluminConfig.java
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/config/OutputMetricsConfig.java // @Data // public static class OutputMetricsFluentdConfig { // public static final String DEFAULT_ENABLED = "false"; // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_TIMEOUT = "3000"; // public static final String DEFAULT_BUFFER_CAPACITY = "1048576"; // public static final String DEFAULT_TAG = "relumin"; // public static final String DEFAULT_NODE_TAG = "node"; // // private String enabled; // private String host; // private String port; // private String timeout; // private String bufferCapacity; // private String tag; // private String nodeTag; // }
import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.config.OutputMetricsConfig.OutputMetricsFluentdConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import static org.apache.commons.lang3.StringUtils.*;
"redis.port", redis.getPort()); // scheduler prop.setProperty( "scheduler.refreshClustersIntervalMillis", defaultIfBlank( scheduler.getRefreshClustersIntervalMillis(), SchedulerConfig.DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS)); prop.setProperty( "scheduler.collectStaticsInfoIntervalMillis", defaultIfBlank( scheduler.getCollectStaticsInfoIntervalMillis(), SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS)); prop.setProperty( "scheduler.collectStaticsInfoMaxCount", defaultIfBlank( scheduler.getCollectStaticsInfoMaxCount(), SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT)); prop.setProperty( "scheduler.collectSlowLogMaxCount", defaultIfBlank( scheduler.getCollectStaticsInfoMaxCount(), SchedulerConfig.DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT)); // notice email prop.setProperty( "notice.mail.host", defaultIfBlank( notice.getMail().getHost(),
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/config/OutputMetricsConfig.java // @Data // public static class OutputMetricsFluentdConfig { // public static final String DEFAULT_ENABLED = "false"; // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_TIMEOUT = "3000"; // public static final String DEFAULT_BUFFER_CAPACITY = "1048576"; // public static final String DEFAULT_TAG = "relumin"; // public static final String DEFAULT_NODE_TAG = "node"; // // private String enabled; // private String host; // private String port; // private String timeout; // private String bufferCapacity; // private String tag; // private String nodeTag; // } // Path: src/main/java/com/behase/relumin/config/ReluminConfig.java import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.config.OutputMetricsConfig.OutputMetricsFluentdConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import static org.apache.commons.lang3.StringUtils.*; "redis.port", redis.getPort()); // scheduler prop.setProperty( "scheduler.refreshClustersIntervalMillis", defaultIfBlank( scheduler.getRefreshClustersIntervalMillis(), SchedulerConfig.DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS)); prop.setProperty( "scheduler.collectStaticsInfoIntervalMillis", defaultIfBlank( scheduler.getCollectStaticsInfoIntervalMillis(), SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS)); prop.setProperty( "scheduler.collectStaticsInfoMaxCount", defaultIfBlank( scheduler.getCollectStaticsInfoMaxCount(), SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT)); prop.setProperty( "scheduler.collectSlowLogMaxCount", defaultIfBlank( scheduler.getCollectStaticsInfoMaxCount(), SchedulerConfig.DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT)); // notice email prop.setProperty( "notice.mail.host", defaultIfBlank( notice.getMail().getHost(),
NoticeMailConfig.DEFAULT_HOST));
be-hase/relumin
src/main/java/com/behase/relumin/config/ReluminConfig.java
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/config/OutputMetricsConfig.java // @Data // public static class OutputMetricsFluentdConfig { // public static final String DEFAULT_ENABLED = "false"; // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_TIMEOUT = "3000"; // public static final String DEFAULT_BUFFER_CAPACITY = "1048576"; // public static final String DEFAULT_TAG = "relumin"; // public static final String DEFAULT_NODE_TAG = "node"; // // private String enabled; // private String host; // private String port; // private String timeout; // private String bufferCapacity; // private String tag; // private String nodeTag; // }
import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.config.OutputMetricsConfig.OutputMetricsFluentdConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import static org.apache.commons.lang3.StringUtils.*;
"notice.mail.port", defaultIfBlank( notice.getMail().getPort(), NoticeMailConfig.DEFAULT_PORT)); prop.setProperty( "notice.mail.user", defaultIfBlank( notice.getMail().getUser(), NoticeMailConfig.DEFAULT_USER)); prop.setProperty( "notice.mail.password", defaultIfBlank( notice.getMail().getPassword(), NoticeMailConfig.DEFAULT_PASSWORD)); prop.setProperty( "notice.mail.from", defaultIfBlank( notice.getMail().getFrom(), NoticeMailConfig.DEFAULT_FROM)); prop.setProperty( "notice.mail.charset", defaultIfBlank( notice.getMail().getCharset(), NoticeMailConfig.DEFAULT_CHARSET)); // fluentd prop.setProperty( "outputMetrics.fluentd.enabled", defaultIfBlank( outputMetrics.getFluentd().getEnabled(),
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/config/OutputMetricsConfig.java // @Data // public static class OutputMetricsFluentdConfig { // public static final String DEFAULT_ENABLED = "false"; // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_TIMEOUT = "3000"; // public static final String DEFAULT_BUFFER_CAPACITY = "1048576"; // public static final String DEFAULT_TAG = "relumin"; // public static final String DEFAULT_NODE_TAG = "node"; // // private String enabled; // private String host; // private String port; // private String timeout; // private String bufferCapacity; // private String tag; // private String nodeTag; // } // Path: src/main/java/com/behase/relumin/config/ReluminConfig.java import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.config.OutputMetricsConfig.OutputMetricsFluentdConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import static org.apache.commons.lang3.StringUtils.*; "notice.mail.port", defaultIfBlank( notice.getMail().getPort(), NoticeMailConfig.DEFAULT_PORT)); prop.setProperty( "notice.mail.user", defaultIfBlank( notice.getMail().getUser(), NoticeMailConfig.DEFAULT_USER)); prop.setProperty( "notice.mail.password", defaultIfBlank( notice.getMail().getPassword(), NoticeMailConfig.DEFAULT_PASSWORD)); prop.setProperty( "notice.mail.from", defaultIfBlank( notice.getMail().getFrom(), NoticeMailConfig.DEFAULT_FROM)); prop.setProperty( "notice.mail.charset", defaultIfBlank( notice.getMail().getCharset(), NoticeMailConfig.DEFAULT_CHARSET)); // fluentd prop.setProperty( "outputMetrics.fluentd.enabled", defaultIfBlank( outputMetrics.getFluentd().getEnabled(),
OutputMetricsFluentdConfig.DEFAULT_ENABLED));
be-hase/relumin
src/main/java/com/behase/relumin/controller/UserApiController.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/UserApiController.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired
private UserService userService;
be-hase/relumin
src/main/java/com/behase/relumin/controller/UserApiController.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired private UserService userService; @Autowired
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/UserApiController.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired private UserService userService; @Autowired
private LoggingOperationService loggingOperationService;
be-hase/relumin
src/main/java/com/behase/relumin/controller/UserApiController.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired private UserService userService; @Autowired private LoggingOperationService loggingOperationService; @RequestMapping(value = "/users", method = RequestMethod.GET)
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/UserApiController.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; package com.behase.relumin.controller; //@Slf4j @RestController @RequestMapping(value = "/api") public class UserApiController { @Autowired private UserService userService; @Autowired private LoggingOperationService loggingOperationService; @RequestMapping(value = "/users", method = RequestMethod.GET)
public List<LoginUser> users() throws Exception {
be-hase/relumin
src/main/java/com/behase/relumin/controller/UserApiController.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
@PathVariable String username, @RequestParam(defaultValue = "") String displayName, @RequestParam(defaultValue = "") String role, @RequestParam(defaultValue = "") String password ) throws Exception { loggingOperationService.log("addUser", authentication, "username={}, displayName={}, role={}.", username, displayName, role); userService.addUser(username, displayName, password, role); return userService.getUser(username); } @RequestMapping(value = "/user/{username}/update", method = RequestMethod.POST) public LoginUser update( Authentication authentication, @PathVariable String username, @RequestParam(defaultValue = "") String displayName, @RequestParam(defaultValue = "") String role ) throws Exception { loggingOperationService.log("updateUser", authentication, "username={}, displayName={}, role={}.", username, displayName, role); userService.updateUser(username, displayName, role); return userService.getUser(username); } @RequestMapping(value = "/me/update", method = RequestMethod.POST) public LoginUser updateMe( Authentication authentication, @RequestParam(defaultValue = "") String displayName ) throws Exception { if (authentication == null) {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/LoggingOperationService.java // public interface LoggingOperationService { // void log(String operationName, Authentication authentication); // // void log(String operationName, Authentication authentication, String msg); // // void log(String operationName, Authentication authentication, String msg, Object... objects); // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/UserApiController.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.LoggingOperationService; import com.behase.relumin.service.UserService; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @PathVariable String username, @RequestParam(defaultValue = "") String displayName, @RequestParam(defaultValue = "") String role, @RequestParam(defaultValue = "") String password ) throws Exception { loggingOperationService.log("addUser", authentication, "username={}, displayName={}, role={}.", username, displayName, role); userService.addUser(username, displayName, password, role); return userService.getUser(username); } @RequestMapping(value = "/user/{username}/update", method = RequestMethod.POST) public LoginUser update( Authentication authentication, @PathVariable String username, @RequestParam(defaultValue = "") String displayName, @RequestParam(defaultValue = "") String role ) throws Exception { loggingOperationService.log("updateUser", authentication, "username={}, displayName={}, role={}.", username, displayName, role); userService.updateUser(username, displayName, role); return userService.getUser(username); } @RequestMapping(value = "/me/update", method = RequestMethod.POST) public LoginUser updateMe( Authentication authentication, @RequestParam(defaultValue = "") String displayName ) throws Exception { if (authentication == null) {
throw new InvalidParameterException("You are not loggedin.");
be-hase/relumin
src/main/java/com/behase/relumin/webconfig/WebSecurityConfig.java
// Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // }
import com.behase.relumin.model.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.StandardPasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
package com.behase.relumin.webconfig; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Value("${auth.enabled}") private boolean authEnabled; @Value("${auth.allowAnonymous}") private boolean authAllowAnonymous; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().disable(); if (authEnabled) { http .rememberMe() .tokenRepository(new InMemoryTokenRepositoryImpl()) .tokenValiditySeconds(Integer.MAX_VALUE).and() .authorizeRequests() .antMatchers("/login", "/css/**", "/js/**", "/img/**", "**/favicon.ico", "/vendor/**") .permitAll() .antMatchers(HttpMethod.POST, "/api/cluster/*", "/api/cluster/*/delete", "/api/cluster/*/notice")
// Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // Path: src/main/java/com/behase/relumin/webconfig/WebSecurityConfig.java import com.behase.relumin.model.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.StandardPasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; package com.behase.relumin.webconfig; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Value("${auth.enabled}") private boolean authEnabled; @Value("${auth.allowAnonymous}") private boolean authAllowAnonymous; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().disable(); if (authEnabled) { http .rememberMe() .tokenRepository(new InMemoryTokenRepositoryImpl()) .tokenValiditySeconds(Integer.MAX_VALUE).and() .authorizeRequests() .antMatchers("/login", "/css/**", "/js/**", "/img/**", "**/favicon.ico", "/vendor/**") .permitAll() .antMatchers(HttpMethod.POST, "/api/cluster/*", "/api/cluster/*/delete", "/api/cluster/*/notice")
.hasAuthority(Role.RELUMIN_ADMIN.getAuthority())
be-hase/relumin
src/test/java/com/behase/relumin/controller/MyControllerAdviceTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyControllerAdviceTest { @InjectMocks @Spy private MyControllerAdvice advice = new MyControllerAdvice(); @Rule public OutputCapture capture = new OutputCapture(); @Test public void allExceptionHandler() {
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/test/java/com/behase/relumin/controller/MyControllerAdviceTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyControllerAdviceTest { @InjectMocks @Spy private MyControllerAdvice advice = new MyControllerAdvice(); @Rule public OutputCapture capture = new OutputCapture(); @Test public void allExceptionHandler() {
ResponseEntity<ErrorResponse> result = advice.allExceptionHandler(
be-hase/relumin
src/test/java/com/behase/relumin/controller/MyControllerAdviceTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyControllerAdviceTest { @InjectMocks @Spy private MyControllerAdvice advice = new MyControllerAdvice(); @Rule public OutputCapture capture = new OutputCapture(); @Test public void allExceptionHandler() { ResponseEntity<ErrorResponse> result = advice.allExceptionHandler( new Exception(), null, null ); assertThat(result.getBody().getError().getCode(), is("500")); assertThat(result.getBody().getError().getMessage(), is("Internal server error.")); } @Test public void missingServletRequestParameterExceptionHandler() { ErrorResponse result = advice.missingServletRequestParameterExceptionHandler( new MissingServletRequestParameterException("", ""), null, null ); assertThat(result.getError().getCode(), is("400")); assertThat(result.getError().getMessage(), is("Invalid parameter.")); } @Test public void apiExceptionHandler_5xx() { ResponseEntity<ErrorResponse> result = advice.apiExceptionHandler(
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/test/java/com/behase/relumin/controller/MyControllerAdviceTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyControllerAdviceTest { @InjectMocks @Spy private MyControllerAdvice advice = new MyControllerAdvice(); @Rule public OutputCapture capture = new OutputCapture(); @Test public void allExceptionHandler() { ResponseEntity<ErrorResponse> result = advice.allExceptionHandler( new Exception(), null, null ); assertThat(result.getBody().getError().getCode(), is("500")); assertThat(result.getBody().getError().getMessage(), is("Internal server error.")); } @Test public void missingServletRequestParameterExceptionHandler() { ErrorResponse result = advice.missingServletRequestParameterExceptionHandler( new MissingServletRequestParameterException("", ""), null, null ); assertThat(result.getError().getCode(), is("400")); assertThat(result.getError().getMessage(), is("Invalid parameter.")); } @Test public void apiExceptionHandler_5xx() { ResponseEntity<ErrorResponse> result = advice.apiExceptionHandler(
new ApiException("500", "error", HttpStatus.INTERNAL_SERVER_ERROR), null, null
be-hase/relumin
src/main/java/com/behase/relumin/exception/InvalidParameterException.java
// Path: src/main/java/com/behase/relumin/Constants.java // public class Constants { // private Constants() { // } // // ; // // public static final int ALL_SLOTS_SIZE = 16384; // // public static final String ERR_CODE_INVALID_PARAMETER = "400_000"; // public static final String ERR_CODE_REDIS_SET_FAILED = "500_000"; // public static final String ERR_CODE_ALL_NODE_DOWN = "500_001"; // public static final String ERR_CODE_CLUSTER_NOT_AGREE_CONFIG = "500_002"; // public static final String ERR_CODE_CLUSTER_HAS_OPEN_SLOTS = "500_003"; // public static final String ERR_CODE_CLUSTER_HAS_ERRORS = "500_004"; // public static final String ERR_CODE_UNKNOWN = "500_999"; // // public static String getUsersRedisKey(String prefixKey) { // return Joiner.on(".").join(prefixKey, "users").toString(); // } // // public static String getClustersRedisKey(String prefixKey) { // return Joiner.on(".").join(prefixKey, "clusters").toString(); // } // // public static String getClusterRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName).toString(); // } // // public static String getClusterNoticeRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "notice").toString(); // } // // public static String getNodeRedisKey(String prefixKey, String clusterName, String nodeId) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "node", nodeId).toString(); // } // // public static String getNodeStaticsInfoRedisKey(String prefixKey, String clusterName, String nodeId) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "node", nodeId, "staticsInfo").toString(); // } // // public static String getClusterSlowLogRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "slowLog").toString(); // } // }
import com.behase.relumin.Constants; import org.springframework.http.HttpStatus;
package com.behase.relumin.exception; public class InvalidParameterException extends ApiException { private static final long serialVersionUID = -6416726302671334601L; public InvalidParameterException(String message) {
// Path: src/main/java/com/behase/relumin/Constants.java // public class Constants { // private Constants() { // } // // ; // // public static final int ALL_SLOTS_SIZE = 16384; // // public static final String ERR_CODE_INVALID_PARAMETER = "400_000"; // public static final String ERR_CODE_REDIS_SET_FAILED = "500_000"; // public static final String ERR_CODE_ALL_NODE_DOWN = "500_001"; // public static final String ERR_CODE_CLUSTER_NOT_AGREE_CONFIG = "500_002"; // public static final String ERR_CODE_CLUSTER_HAS_OPEN_SLOTS = "500_003"; // public static final String ERR_CODE_CLUSTER_HAS_ERRORS = "500_004"; // public static final String ERR_CODE_UNKNOWN = "500_999"; // // public static String getUsersRedisKey(String prefixKey) { // return Joiner.on(".").join(prefixKey, "users").toString(); // } // // public static String getClustersRedisKey(String prefixKey) { // return Joiner.on(".").join(prefixKey, "clusters").toString(); // } // // public static String getClusterRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName).toString(); // } // // public static String getClusterNoticeRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "notice").toString(); // } // // public static String getNodeRedisKey(String prefixKey, String clusterName, String nodeId) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "node", nodeId).toString(); // } // // public static String getNodeStaticsInfoRedisKey(String prefixKey, String clusterName, String nodeId) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "node", nodeId, "staticsInfo").toString(); // } // // public static String getClusterSlowLogRedisKey(String prefixKey, String clusterName) { // return Joiner.on(".").join(prefixKey, "cluster", clusterName, "slowLog").toString(); // } // } // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java import com.behase.relumin.Constants; import org.springframework.http.HttpStatus; package com.behase.relumin.exception; public class InvalidParameterException extends ApiException { private static final long serialVersionUID = -6416726302671334601L; public InvalidParameterException(String message) {
super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST);
be-hase/relumin
src/test/java/com/behase/relumin/support/JedisSupportTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Spy; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat;
@Test public void parseClusterInfoResult() { // given String clusterInfoText = "" + "cluster_state:fail\n" + "cluster_slots_assigned:0\n" + "cluster_slots_ok:0"; // when Map<String, String> result = tested.parseClusterInfoResult(clusterInfoText); // then assertThat(result, hasEntry("cluster_state", "fail")); assertThat(result, hasEntry("cluster_slots_assigned", "0")); assertThat(result, hasEntry("cluster_slots_ok", "0")); } @Test public void parseClusterNodesResult() { // given String clusterNodesText = "" + "7893f01887835a6e19b09ff663909fced0744926 127.0.0.1:7001 myself,master - 0 0 1 connected 0-2000 2001-4094 4095 [93-<-292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f] [77->-e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca]\n" + "9bd5a779d5981cee7d561dc2bfc984ffbfc744d3 192.168.99.100:7002 slave 4e97c7f8fc08d2bb3e45571c4f001a7a347cbbe2 0 1459242326643 5 disconnected\n" + "c3c0b2b7d7d50e339565de468e7ebd7db79a1ea5 192.168.99.100:7003 master - 0 1459242325640 3 connected 8192-12287\n" + "20e7c57506199c468b0672fda7b00d12a2d6a547 192.168.99.100:7004 slave a4f318b3fb0affd5d130b29cb6161a7e225216b5 0 1459242324639 6 connected\n" + "8e309bc36225a6bfd46ede7ff377b54e0bdbfc5d 192.168.99.101:7001 slave 7893f01887835a6e19b09ff663909fced0744926 0 1459242328644 1 connected\n" + "4e97c7f8fc08d2bb3e45571c4f001a7a347cbbe2 192.168.99.101:7002 master - 0 1459242323638 5 connected 4096-8191\n" + "7040f0339855ff0faf1abeb32baad0d6441e8e2f 192.168.99.101:7003 slave c3c0b2b7d7d50e339565de468e7ebd7db79a1ea5 0 1459242327643 3 connected\n" + "a4f318b3fb0affd5d130b29cb6161a7e225216b5 192.168.99.101:7004 master - 0 1459242328644 6 connected 12288-16383";
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/test/java/com/behase/relumin/support/JedisSupportTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Spy; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; @Test public void parseClusterInfoResult() { // given String clusterInfoText = "" + "cluster_state:fail\n" + "cluster_slots_assigned:0\n" + "cluster_slots_ok:0"; // when Map<String, String> result = tested.parseClusterInfoResult(clusterInfoText); // then assertThat(result, hasEntry("cluster_state", "fail")); assertThat(result, hasEntry("cluster_slots_assigned", "0")); assertThat(result, hasEntry("cluster_slots_ok", "0")); } @Test public void parseClusterNodesResult() { // given String clusterNodesText = "" + "7893f01887835a6e19b09ff663909fced0744926 127.0.0.1:7001 myself,master - 0 0 1 connected 0-2000 2001-4094 4095 [93-<-292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f] [77->-e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca]\n" + "9bd5a779d5981cee7d561dc2bfc984ffbfc744d3 192.168.99.100:7002 slave 4e97c7f8fc08d2bb3e45571c4f001a7a347cbbe2 0 1459242326643 5 disconnected\n" + "c3c0b2b7d7d50e339565de468e7ebd7db79a1ea5 192.168.99.100:7003 master - 0 1459242325640 3 connected 8192-12287\n" + "20e7c57506199c468b0672fda7b00d12a2d6a547 192.168.99.100:7004 slave a4f318b3fb0affd5d130b29cb6161a7e225216b5 0 1459242324639 6 connected\n" + "8e309bc36225a6bfd46ede7ff377b54e0bdbfc5d 192.168.99.101:7001 slave 7893f01887835a6e19b09ff663909fced0744926 0 1459242328644 1 connected\n" + "4e97c7f8fc08d2bb3e45571c4f001a7a347cbbe2 192.168.99.101:7002 master - 0 1459242323638 5 connected 4096-8191\n" + "7040f0339855ff0faf1abeb32baad0d6441e8e2f 192.168.99.101:7003 slave c3c0b2b7d7d50e339565de468e7ebd7db79a1ea5 0 1459242327643 3 connected\n" + "a4f318b3fb0affd5d130b29cb6161a7e225216b5 192.168.99.101:7004 master - 0 1459242328644 6 connected 12288-16383";
List<ClusterNode> result;
be-hase/relumin
src/test/java/com/behase/relumin/support/JedisSupportTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Spy; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat;
// given slots.clear(); IntStream.rangeClosed(0, 10).forEach(i -> slots.add(i)); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); slots.add(200); slots.add(300); // when, then assertThat(tested.slotsDisplay(slots), is("0-10,50,100-110,200,300")); // given slots.clear(); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); // when, then assertThat(tested.slotsDisplay(slots), is("50,100-110")); // given slots.clear(); IntStream.rangeClosed(0, 10).forEach(i -> slots.add(i)); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); slots.add(200); // when, then assertThat(tested.slotsDisplay(slots), is("0-10,50,100-110,200")); } @Test public void getHostAndPorts_invalid_hostAndPorts_range_then_throw_exception() {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/test/java/com/behase/relumin/support/JedisSupportTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Spy; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; // given slots.clear(); IntStream.rangeClosed(0, 10).forEach(i -> slots.add(i)); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); slots.add(200); slots.add(300); // when, then assertThat(tested.slotsDisplay(slots), is("0-10,50,100-110,200,300")); // given slots.clear(); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); // when, then assertThat(tested.slotsDisplay(slots), is("50,100-110")); // given slots.clear(); IntStream.rangeClosed(0, 10).forEach(i -> slots.add(i)); slots.add(50); IntStream.rangeClosed(100, 110).forEach(i -> slots.add(i)); slots.add(200); // when, then assertThat(tested.slotsDisplay(slots), is("0-10,50,100-110,200")); } @Test public void getHostAndPorts_invalid_hostAndPorts_range_then_throw_exception() {
expectedEx.expect(InvalidParameterException.class);
be-hase/relumin
src/test/java/com/behase/relumin/exception/InvalidParameterExceptionTest.java
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.springframework.http.HttpStatus; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
package com.behase.relumin.exception; public class InvalidParameterExceptionTest { @Test public void constructor() { InvalidParameterException invalidParameterException; invalidParameterException = new InvalidParameterException("message");
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/test/java/com/behase/relumin/exception/InvalidParameterExceptionTest.java import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.springframework.http.HttpStatus; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; package com.behase.relumin.exception; public class InvalidParameterExceptionTest { @Test public void constructor() { InvalidParameterException invalidParameterException; invalidParameterException = new InvalidParameterException("message");
assertThat(invalidParameterException.getErrorResponse(), is(new ErrorResponse("400_000", "Invalid parameter. message")));
be-hase/relumin
src/test/java/com/behase/relumin/controller/MyErrorControllerTest.java
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import javax.servlet.http.HttpServletRequest; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyErrorControllerTest { @InjectMocks @Spy private MyErrorController controller = new MyErrorController(); @Test public void handleError_status_code_is_404_or_url_is_error_path_then_return_404_not_found() throws Exception { HttpServletRequest request;
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/test/java/com/behase/relumin/controller/MyErrorControllerTest.java import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import javax.servlet.http.HttpServletRequest; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class MyErrorControllerTest { @InjectMocks @Spy private MyErrorController controller = new MyErrorController(); @Test public void handleError_status_code_is_404_or_url_is_error_path_then_return_404_not_found() throws Exception { HttpServletRequest request;
ResponseEntity<ErrorResponse> result;
be-hase/relumin
src/test/java/com/behase/relumin/exception/ApiExceptionTest.java
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.springframework.http.HttpStatus; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
package com.behase.relumin.exception; public class ApiExceptionTest { @Test public void constructor() { ApiException apiException;
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/test/java/com/behase/relumin/exception/ApiExceptionTest.java import com.behase.relumin.model.ErrorResponse; import org.junit.Test; import org.springframework.http.HttpStatus; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; package com.behase.relumin.exception; public class ApiExceptionTest { @Test public void constructor() { ApiException apiException;
apiException = new ApiException(new ErrorResponse("400", "message"), HttpStatus.BAD_REQUEST);
be-hase/relumin
src/main/java/com/behase/relumin/scheduler/ClusterScheduler.java
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/service/ClusterService.java // public interface ClusterService { // Set<String> getClusters(); // // Cluster getCluster(String clusterName) throws IOException; // // Cluster getClusterByHostAndPort(String hostAndPort) throws IOException; // // boolean existsClusterName(String clusterName); // // void setCluster(String clusterName, String node) throws IOException; // // void changeClusterName(String clusterName, String newClusterName) throws IOException; // // Notice getClusterNotice(String clusterName) throws IOException; // // void setClusterNotice(String clusterName, Notice notice) throws IOException; // // void deleteCluster(String clusterName); // // void refreshClusters(); // // ClusterNode getActiveClusterNode(String clusterName) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeNodeId(String clusterName, String nodeId) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeHostAndPort(String clusterName, String hostAndPort) throws IOException; // // Map<String, Map<String, List<List<Object>>>> getClusterStaticsInfoHistory(String clusterName, List<String> nodes, // List<String> fields, long start, long end); // // PagerData<SlowLog> getClusterSlowLogHistory(String clusterName, long offset, long limit); // }
import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.service.ClusterService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
package com.behase.relumin.scheduler; @Slf4j @Component @Profile(value = "!test") public class ClusterScheduler { @Autowired
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/service/ClusterService.java // public interface ClusterService { // Set<String> getClusters(); // // Cluster getCluster(String clusterName) throws IOException; // // Cluster getClusterByHostAndPort(String hostAndPort) throws IOException; // // boolean existsClusterName(String clusterName); // // void setCluster(String clusterName, String node) throws IOException; // // void changeClusterName(String clusterName, String newClusterName) throws IOException; // // Notice getClusterNotice(String clusterName) throws IOException; // // void setClusterNotice(String clusterName, Notice notice) throws IOException; // // void deleteCluster(String clusterName); // // void refreshClusters(); // // ClusterNode getActiveClusterNode(String clusterName) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeNodeId(String clusterName, String nodeId) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeHostAndPort(String clusterName, String hostAndPort) throws IOException; // // Map<String, Map<String, List<List<Object>>>> getClusterStaticsInfoHistory(String clusterName, List<String> nodes, // List<String> fields, long start, long end); // // PagerData<SlowLog> getClusterSlowLogHistory(String clusterName, long offset, long limit); // } // Path: src/main/java/com/behase/relumin/scheduler/ClusterScheduler.java import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.service.ClusterService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; package com.behase.relumin.scheduler; @Slf4j @Component @Profile(value = "!test") public class ClusterScheduler { @Autowired
ClusterService clusterService;
be-hase/relumin
src/main/java/com/behase/relumin/scheduler/ClusterScheduler.java
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/service/ClusterService.java // public interface ClusterService { // Set<String> getClusters(); // // Cluster getCluster(String clusterName) throws IOException; // // Cluster getClusterByHostAndPort(String hostAndPort) throws IOException; // // boolean existsClusterName(String clusterName); // // void setCluster(String clusterName, String node) throws IOException; // // void changeClusterName(String clusterName, String newClusterName) throws IOException; // // Notice getClusterNotice(String clusterName) throws IOException; // // void setClusterNotice(String clusterName, Notice notice) throws IOException; // // void deleteCluster(String clusterName); // // void refreshClusters(); // // ClusterNode getActiveClusterNode(String clusterName) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeNodeId(String clusterName, String nodeId) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeHostAndPort(String clusterName, String hostAndPort) throws IOException; // // Map<String, Map<String, List<List<Object>>>> getClusterStaticsInfoHistory(String clusterName, List<String> nodes, // List<String> fields, long start, long end); // // PagerData<SlowLog> getClusterSlowLogHistory(String clusterName, long offset, long limit); // }
import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.service.ClusterService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
package com.behase.relumin.scheduler; @Slf4j @Component @Profile(value = "!test") public class ClusterScheduler { @Autowired ClusterService clusterService; @Scheduled(fixedDelayString = "${scheduler.refreshClustersIntervalMillis:"
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/service/ClusterService.java // public interface ClusterService { // Set<String> getClusters(); // // Cluster getCluster(String clusterName) throws IOException; // // Cluster getClusterByHostAndPort(String hostAndPort) throws IOException; // // boolean existsClusterName(String clusterName); // // void setCluster(String clusterName, String node) throws IOException; // // void changeClusterName(String clusterName, String newClusterName) throws IOException; // // Notice getClusterNotice(String clusterName) throws IOException; // // void setClusterNotice(String clusterName, Notice notice) throws IOException; // // void deleteCluster(String clusterName); // // void refreshClusters(); // // ClusterNode getActiveClusterNode(String clusterName) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeNodeId(String clusterName, String nodeId) throws IOException; // // ClusterNode getActiveClusterNodeWithExcludeHostAndPort(String clusterName, String hostAndPort) throws IOException; // // Map<String, Map<String, List<List<Object>>>> getClusterStaticsInfoHistory(String clusterName, List<String> nodes, // List<String> fields, long start, long end); // // PagerData<SlowLog> getClusterSlowLogHistory(String clusterName, long offset, long limit); // } // Path: src/main/java/com/behase/relumin/scheduler/ClusterScheduler.java import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.service.ClusterService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; package com.behase.relumin.scheduler; @Slf4j @Component @Profile(value = "!test") public class ClusterScheduler { @Autowired ClusterService clusterService; @Scheduled(fixedDelayString = "${scheduler.refreshClustersIntervalMillis:"
+ SchedulerConfig.DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS + "}"
be-hase/relumin
src/main/java/com/behase/relumin/webconfig/WebConfig.java
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/interceptor/AddResponseHeaderInterceptor.java // @Component // public class AddResponseHeaderInterceptor extends HandlerInterceptorAdapter { // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // response.setHeader("Access-Control-Allow-Origin", "*"); // return true; // } // }
import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.interceptor.AddResponseHeaderInterceptor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.fluentd.logger.FluentLogger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import redis.clients.jedis.JedisPool; import java.text.SimpleDateFormat; import java.util.TimeZone;
package com.behase.relumin.webconfig; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { public static final ObjectMapper MAPPER = new ObjectMapper(); static { MAPPER.registerModule(new AfterburnerModule()); MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); format.setTimeZone(TimeZone.getTimeZone("UTC")); MAPPER.setDateFormat(format); } @Autowired
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/interceptor/AddResponseHeaderInterceptor.java // @Component // public class AddResponseHeaderInterceptor extends HandlerInterceptorAdapter { // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // response.setHeader("Access-Control-Allow-Origin", "*"); // return true; // } // } // Path: src/main/java/com/behase/relumin/webconfig/WebConfig.java import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.interceptor.AddResponseHeaderInterceptor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.fluentd.logger.FluentLogger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import redis.clients.jedis.JedisPool; import java.text.SimpleDateFormat; import java.util.TimeZone; package com.behase.relumin.webconfig; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { public static final ObjectMapper MAPPER = new ObjectMapper(); static { MAPPER.registerModule(new AfterburnerModule()); MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); format.setTimeZone(TimeZone.getTimeZone("UTC")); MAPPER.setDateFormat(format); } @Autowired
private AddResponseHeaderInterceptor addResponseHeaderInterceptor;
be-hase/relumin
src/main/java/com/behase/relumin/webconfig/WebConfig.java
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/interceptor/AddResponseHeaderInterceptor.java // @Component // public class AddResponseHeaderInterceptor extends HandlerInterceptorAdapter { // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // response.setHeader("Access-Control-Allow-Origin", "*"); // return true; // } // }
import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.interceptor.AddResponseHeaderInterceptor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.fluentd.logger.FluentLogger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import redis.clients.jedis.JedisPool; import java.text.SimpleDateFormat; import java.util.TimeZone;
registrationBean.addUrlPatterns("/*"); registrationBean.setOrder(0); return registrationBean; } @Bean(name = "datastoreRedis", destroyMethod = "destroy") public JedisPool jedisPool() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(10); config.setMaxIdle(10); config.setMinIdle(5); config.setMaxWaitMillis(3000L); config.setTestOnBorrow(true); JedisPool pool = new JedisPool(config, redisHost, redisPort); return pool; } @Bean public MailSender JavaMailSenderImpl() { boolean notNotifyByMail = StringUtils.isBlank(noticeMailHost) || noticeMailPort == 0; if (notNotifyByMail) { return null; } JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(noticeMailHost); mailSender.setPort(noticeMailPort);
// Path: src/main/java/com/behase/relumin/config/NoticeConfig.java // @Data // public static class NoticeMailConfig { // public static final String DEFAULT_HOST = ""; // public static final String DEFAULT_PORT = "0"; // public static final String DEFAULT_USER = ""; // public static final String DEFAULT_PASSWORD = ""; // public static final String DEFAULT_CHARSET = "UTF-8"; // public static final String DEFAULT_FROM = ""; // // private String host; // private String port; // private String user; // private String password; // private String charset; // // private String from; // } // // Path: src/main/java/com/behase/relumin/interceptor/AddResponseHeaderInterceptor.java // @Component // public class AddResponseHeaderInterceptor extends HandlerInterceptorAdapter { // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // response.setHeader("Access-Control-Allow-Origin", "*"); // return true; // } // } // Path: src/main/java/com/behase/relumin/webconfig/WebConfig.java import com.behase.relumin.config.NoticeConfig.NoticeMailConfig; import com.behase.relumin.interceptor.AddResponseHeaderInterceptor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.fluentd.logger.FluentLogger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import redis.clients.jedis.JedisPool; import java.text.SimpleDateFormat; import java.util.TimeZone; registrationBean.addUrlPatterns("/*"); registrationBean.setOrder(0); return registrationBean; } @Bean(name = "datastoreRedis", destroyMethod = "destroy") public JedisPool jedisPool() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(10); config.setMaxIdle(10); config.setMinIdle(5); config.setMaxWaitMillis(3000L); config.setTestOnBorrow(true); JedisPool pool = new JedisPool(config, redisHost, redisPort); return pool; } @Bean public MailSender JavaMailSenderImpl() { boolean notNotifyByMail = StringUtils.isBlank(noticeMailHost) || noticeMailPort == 0; if (notNotifyByMail) { return null; } JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(noticeMailHost); mailSender.setPort(noticeMailPort);
mailSender.setDefaultEncoding(StringUtils.defaultString(noticeMailCharset, NoticeMailConfig.DEFAULT_CHARSET));
be-hase/relumin
src/main/java/com/behase/relumin/support/TribClusterNode.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.Jedis; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.stream.Collectors;
package com.behase.relumin.support; /** * Almost clone of redis-trib.rb (ClusterNode) * * @author Ryosuke Hasebe */ @Slf4j public class TribClusterNode implements Closeable { private Jedis jedis;
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/main/java/com/behase/relumin/support/TribClusterNode.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.Jedis; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; package com.behase.relumin.support; /** * Almost clone of redis-trib.rb (ClusterNode) * * @author Ryosuke Hasebe */ @Slf4j public class TribClusterNode implements Closeable { private Jedis jedis;
private ClusterNode nodeInfo;
be-hase/relumin
src/main/java/com/behase/relumin/support/TribClusterNode.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.Jedis; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.stream.Collectors;
package com.behase.relumin.support; /** * Almost clone of redis-trib.rb (ClusterNode) * * @author Ryosuke Hasebe */ @Slf4j public class TribClusterNode implements Closeable { private Jedis jedis; private ClusterNode nodeInfo; private Map<String, String> clusterInfo = Maps.newHashMap(); private boolean dirty; private List<ClusterNode> friends = Lists.newArrayList(); private Set<Integer> tmpSlots = Sets.newTreeSet(); private List<TribClusterNode> replicas = Lists.newArrayList(); public TribClusterNode(String hostAndPort) { String[] hostAndPortArray = StringUtils.split(hostAndPort, ":"); if (hostAndPortArray.length < 2) {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // Path: src/main/java/com/behase/relumin/support/TribClusterNode.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.Jedis; import java.io.Closeable; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; package com.behase.relumin.support; /** * Almost clone of redis-trib.rb (ClusterNode) * * @author Ryosuke Hasebe */ @Slf4j public class TribClusterNode implements Closeable { private Jedis jedis; private ClusterNode nodeInfo; private Map<String, String> clusterInfo = Maps.newHashMap(); private boolean dirty; private List<ClusterNode> friends = Lists.newArrayList(); private Set<Integer> tmpSlots = Sets.newTreeSet(); private List<TribClusterNode> replicas = Lists.newArrayList(); public TribClusterNode(String hostAndPort) { String[] hostAndPortArray = StringUtils.split(hostAndPort, ":"); if (hostAndPortArray.length < 2) {
throw new InvalidParameterException("Invalid IP or Port. Use IP:Port format");
be-hase/relumin
src/test/java/com/behase/relumin/util/ValidationUtilsTest.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // }
import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List;
package com.behase.relumin.util; public class ValidationUtilsTest { @Test(expected = InvalidParameterException.class) public void createClusterParam_need_3master() {
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // } // Path: src/test/java/com/behase/relumin/util/ValidationUtilsTest.java import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List; package com.behase.relumin.util; public class ValidationUtilsTest { @Test(expected = InvalidParameterException.class) public void createClusterParam_need_3master() {
CreateClusterParam param1 = new CreateClusterParam();
be-hase/relumin
src/test/java/com/behase/relumin/controller/WebControllerTest.java
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/WebControllerTest.java import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock
private UserService userService;
be-hase/relumin
src/test/java/com/behase/relumin/controller/WebControllerTest.java
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock private UserService userService; @Before public void init() { Whitebox.setInternalState(controller, "buildNumber", "1"); Whitebox.setInternalState(controller, "collectStaticsInfoIntervalMillis", "1"); Whitebox.setInternalState(controller, "authEnabled", true); Whitebox.setInternalState(controller, "authAllowAnonymous", true); } @Test public void index_with_auth() throws Exception { ExtendedModelMap model = new ExtendedModelMap(); Authentication authentication = mock(Authentication.class);
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/WebControllerTest.java import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock private UserService userService; @Before public void init() { Whitebox.setInternalState(controller, "buildNumber", "1"); Whitebox.setInternalState(controller, "collectStaticsInfoIntervalMillis", "1"); Whitebox.setInternalState(controller, "authEnabled", true); Whitebox.setInternalState(controller, "authAllowAnonymous", true); } @Test public void index_with_auth() throws Exception { ExtendedModelMap model = new ExtendedModelMap(); Authentication authentication = mock(Authentication.class);
doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString());